Discover the most recent date of a document by analyzing two distinct fields: the month and the year

In my mongoDB database, the documents have the following structure:

{username:String, paymentYear:Int, paymentMonth:Int}

I am trying to retrieve the latest document for a specific username, which would be the one with the date closest to the current Date.now() value. What would be the most effective approach for achieving this? Is there a specific mongoDB query I can utilize, or should I develop custom code for this task?

Appreciate any assistance. Thank you.

Answer №1

You can achieve this functionality by utilizing MongoDB's $dateFromParts stage within the Aggregation pipeline.

db.test.aggregate([
    {
        "$addFields": {
            "tempDate": {
                "$dateFromParts": {
                  year : '$paymentYear', 
                  month : '$paymentMonth',
                }
            }
        }
    },
    {
        "$sort": {"tempDate": -1}  // Update from `-1` to `1` for Ascending Order
    },
    {
        "$limit": 1 // Specify the number of documents to return based on the sort order
    },
])

Alternatively, you can incorporate this logic in the $project stage instead of using $addFields depending on your specific requirements for optimized performance.

Keep in mind that this functionality is compatible only with MongoDB version 3.6 and later.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

Neglect to notify about the input text's value

Having trouble retrieving the text from a simple <input id="editfileFormTitleinput" type="text>. Despite my efforts, I am unable to alert the content within the input field. This is the code snippet I've attempted: $('#editfileFormTitleinp ...

Desiring to iterate through an array of identification numbers in order to retrieve information from an external API

I have been working on an app where I retrieve IDs from one API and pass them into a second API to display the property overviewList.overview.lifeTimeData.energy for each ID. However, in my current setup, I am only able to display the property of the fir ...

Messages in a designated channel that are automatically erased

I have set up a suggestion channel where users can only post links, and the bot will react based on what they post. I've managed to make the bot automatically react to links, but I'm struggling to get it to delete anything that is not a link. I w ...

Is it possible to store a randomly generated variable in JavaScript for future reference?

Currently, I am involved in a project that involves generating random variables to create unique scenes. One specific variable is the location of these scenes. My goal is to be able to generate a location with just one button click. Subsequently, by pressi ...

After deploying to Heroku, I encountered a 404 Not Found error when trying to access my app

I have been spending the entire day working on deploying my MERN stack application to Heroku. It runs smoothly when I test it locally, but once deployed on Heroku, I encounter a 404 error when trying to interact with MongoDB Atlas. I attempted removing th ...

Steps to make background color transparent in Phaser 3

Issue I encountered a problem when adding two Text objects to a scene. The background color of the latter one could not be set to transparent. Is there anyone who can assist me with this? Below is a screenshot for reference. Attempted Solutions I at ...

Mongoose: Updating an array property with new values

Is there a way to replace an array property in a document with values from another array? Schema: var postSchema = new mongoose.Schema({ title: { type: String, required: true, index: { unique: true } }, content: { type: String }, tags: [{ typ ...

ASP TextChanged event is not triggering unless the user presses the Enter key or tabs out

My code is functioning correctly, however, the TextChanged event is triggered when I press enter or tab, causing my code to execute. I would like to be able to search for a record without having to press enter or tab. ASP: asp:TextBox ID="txtNameSearch ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

Setting up CloudKitJS Server-to-Server Communication

I'm struggling to make this work. I keep encountering the following error message: [Error: No key provided to sign] Below is my configuration code: CloudKit.configure({ services: { fetch: fetch }, containers: [{ containerIdentifier: & ...

Unable to determine the reason why the JavaScript plugin is not functioning as expected

I have been attempting to set up a JS modal window and have essentially copied the code for the plugin exactly as instructed, but it is not functioning properly. Here is my code... <!doctype html> <html> <head> <meta charset="utf- ...

Verify if the form has been successfully validated

Here is a simple form using Tag Helper: <form asp-area="Admin" asp-controller="Categories" asp-action="EditCategory" method="post" id="CategoryForm"> <div class="row"> ...

Does the global $.ajaxSetup() function not impact $.ajax() calls within distinct functions?

Is it possible to make the effects of $.ajaxSetup() reach into function bodies? I'm having trouble getting $.ajaxSetup() to impact the $.ajax() calls within functions. Here is an example: In the code snippet below, the ajax request made by function f ...

When sorting in AngularJS using the orderBy filter, remember that string values should come before numeric values: for example, sort as follows (n/a, 0,

While running an AngularJS filter sorting on a table, I encountered an issue where if the value is 'n/a' (which is a numeric string), the sorting is incorrect. I expected the order to be n/a, 0, 1, 2, 5, 100 since strings should be considered l ...

search for a specific value within a nested subfield of an asterisk star field in Firestore

Here is the data I have: { root: { _rEG: { fen: 'value' }, _AS: { fen: 'value' }, _BSSA: { fen: 'value' } } } I would like to query using where('root.*.fen', '==', 'value'). ...

Switch up the Angular base URL using ngx-translate

I successfully integrated ngx-translate into my Angular project. Now, I want to dynamically change the base href based on the language selected from the header menu. Currently, the URL appears as: "localhost:4200". However, upon launching the project, it ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

How to continuously animate images in HTML using Bootstrap

I want to showcase 7-8 client images in a continuous loop using a <marquee> tag. The issue is that there is a gap between the last and first images. Here is the HTML code I have: <marquee> <ul> <li><a href="#&q ...

A different approach to fixing the error "Uncaught (in promise) TypeError: fs.writeFile is not a function" in TensorFlow.js when running on Chrome

I've been attempting to export a variable in the TensorFlow posenet model while it's running in the Chrome browser using the code snippet below. After going through various discussions, I discovered that exporting a variable with fswritefile in t ...