Issue with Mongoose $gte operator functionality in date comparison

I'm facing an issue while trying to create a query for the past week in mongoDB. The current query is not producing the expected results.

[{
    $lookup: {
        from: 'reviews',
        localField: 'groupReviews',
        foreignField: '_id',
        as: 'groupReviews'
    }
}, {
    $match: {
        $and: [{
                _id: {
                    $eq: ObjectId('5f247eea8ad8eb53883f4a9b')
                }
            },
            {
                "groupReviews.reviewCreated": {
                    $gte: ISODate('2020-06-20T10:24:51.303Z')
                }
            }
        ]
    }
}, {
    $project: {
        count: {
            $size: "$groupReviews",
        },
        groupReviews: {
            $slice: ["$groupReviews", 0, 20],
        }
    }
}, {
    $sort: {
        "groupReviews.reviewCreated": -1
    }
}]

Current result: the code is fetching data older than 2020-06-20.

Expected result: it should only display records newer than 2020-06-20.

I have included an image below for better understanding:

Image Link

Answer №1

When using the $match stage in MongoDB, it will match entire documents rather than individual array elements. If any element in the array meets the specified $gte condition, the document will be matched and continue through the pipeline.

If you need to remove specific array elements older than a certain date, there are a couple of options:

  • $unwind the array before matching and then use $group to reconstruct it with only the relevant entries
  • Alternatively, utilize the $filter operator within your $project stage to eliminate unwanted elements prior to manipulation

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

How can I retrieve information from a MySQL Table and display it on an HTML page?

Seeking Solution, I've experimented with Node.JS, but unfortunately, it does not seem suitable for webpage functionality. Online resources mostly discuss displaying HTML through Node.JS without mentioning SQL integration. My experience with PHP is l ...

Store a collection of objects in Firebase while ensuring that the keys are unique and not numbered sequentially

I have an array of JavaScript objects structured like this: jsObjFromCsv = [ { "J251525" : { "APPROVER" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8edac1c3cec3cfc7c2a0cdc1c3">[email pr ...

Is it possible for WebSockets to serve as a substitute for AJAX for handling Database requests?

I have recently made the switch on my website from using the EventSource Polling constructor to the WebSocket standard in Node.js. Originally, all backend work on my site was done with PHP, but I am now trying to transition as much as possible to WebSocket ...

What methods can be utilized to transform a Buffer into a specialized base format?

Is there a way to convert a Buffer into a string representation using a custom base, such as octal, base26, base58, or base64? I found it surprisingly difficult to achieve this without relying on external libraries like BN, and only using NodeJS native fu ...

What is the best way to arrange numerous objects within an array?

Here is the code snippet I am working with: const info = { detail : { id: "1", name: "aa", category: [ { id:"11", order:0, }, { id:"33", order:5, }, { id: ...

Encountering a problem during the creation of a fresh Angular 2 project

After installing AngularJs with the command npm install -g angular-cli, I encountered an error when trying to create a new project: Cannot find module 'reflect-metadata' How can I resolve this error? ...

Having difficulty passing an array using AJAX

One of my current projects involves using a JavaScript function to send an array via AJAX to a PHP script on the server side. Below, I am including relevant excerpts of the code from my JavaScript AJAX function: $.ajax({ url: "bar2.php", type: ...

Access the value of a JavaScript global variable using Selenium in Python

I need to access a value from a global variable in JavaScript: clearInterval(countdownTimerTHx); var saniye_thx = 298 // <--- Variable here function secondPassedTHx() { https://i.sstatic.net/odIbh.png My goal is to retrieve the value " ...

Assign the private members of the class to the arguments of the constructor

class Bar { #one #two #three #four #five #six #seven #eight #nine #ten #eleven #twelve #thirteen #fourteen #fifteen #sixteen constructor( one, two, three, four, five, six, seven, eight, ...

Focusing on the initial element following CSS prioritization

Check out this codepen link: http://codepen.io/muji/pen/XpEYzO I am looking to target the first element after it has been sorted using a CSS "order" property and apply another CSS property to it. Is there a way to use jQuery or any other method to identi ...

Unable to stop React HTMLAudioElement from playing

In the realm of React, there exists a component that requires a URL input to function. The purpose of this component is to display a button that allows users to control the playback of an audio file. It's worth noting that this particular component is ...

MongoDB does not return any results for the query and returns

I am facing an issue while trying to retrieve information from my mongodb database. Despite successfully fetching data from the "users" collection, I keep getting an empty object for other collections. var mongoose = require('mongoose'); var Sch ...

Can you identify the origin of the inclusion of a .php file?

Is there a way to automatically determine if a PHP script is being accessed directly as an HTML page, used as a JavaScript file, or utilized as a CSS Stylesheet? I'm looking for a solution that doesn't involve GET variables or setting a flag wit ...

Updating records in Yii2 MongoDB using regular expressions

My goal is to update data based on a regex condition. However, when I call the update method, nothing gets updated. Here is the code snippet: $collection->update( ['post_barelink' => ['$regex' => '.*shared.com' . ...

What is the best way to adjust a div's height to fill the remaining space of the viewport after the header's height

Is there a way to create a hero section that fills 100vh minus the height of the header, especially when the height of the header is not fixed? I initially used CSS with a height property set to calc(100vh - 310px), where 310px represents the height of t ...

What is the reason why sinon stub is unable to replace the actual exports.function?

I have a situation where my controller async function is calling another async exported function. I am looking to test specific results of the dependent function rather than testing the dependency itself. However, when I try to stub the function, it seems ...

Locate the nearest span element and update its CSS class

On my page, there is a section with the following code: <h5 class="text-center" id="findStore" style="width:260px"> <a data-toggle="collapse" data-parent="#accordion" href="#@item.ProductId" aria-expanded="true" aria-controls="@item.ProductId ...

Tips for transforming the date format in a MySQL stored procedure insert statement from "22-12-2010" to "2010-12-22"

I'm facing an issue where I need to send the registration date parameter to my MySQL database in the format "22-12-2010", however, the SQL date type is in a different format. How can I successfully change the date format to "2010-12-22" and insert it ...

Minimize the length of Java code

I am working on implementing a search column in my project and the code provided below is meant to achieve that. However, I have concerns about the code's efficiency as it appears to be quite lengthy. Is there a way to accomplish the same task with fe ...

Tips for effectively grouping a JavaScript object array with the help of Lodash

I have an array of objects in JavaScript that looks like this: [{ day : "August 30th", id: 1, message : "lorem ipsum1" },{ day : "August 30th", id: 2, message : "lorem ipsum2" },{ day : "August 31th", id: 3, message : " ...