Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo query using aggregation for dates

In the following query I'm trying to find entries in my articles collection made in the last week, sorted by the number of votes on that article. The $match doesn't seem to work(maybe I dont know how to use it). The following query works perfectly, so its not a date format issue,

db.articles.find(timestamp:{
                '$lte':new Date(),
                '$gte':new Date(ISODate().getTime()-7*1000*86400)}
        })

But this one doesn't fetch any results. Without the $match it also fetches the required results(articles sorted by votecount).

db.articles.aggregate([
    {
        $project:{
            _id:1,
            numVotes:{$subtract:[{$size:"$votes.up"},{$size:"$votes.down"}]}}
    },
    {
        $sort:{numVotes:-1}
    },
    {
        $match:{
            timestamp:{
                '$lte':new Date(),
                '$gte':new Date(ISODate().getTime()-7*1000*86400)}
        }
    }
])
like image 603
Ayush Gupta Avatar asked Oct 28 '25 08:10

Ayush Gupta


1 Answers

You are trying to match at the end of your pipeline, which supposes you have projected timestamp field, and you haven't done that.

I believe what you want is to filter data before aggregation, so you should place match at the top of your aggregation array.

Try this:

db.articles.aggregate([{
    $match: {
        timestamp: {
            '$lte': new Date(),
            '$gte': new Date(ISODate().getTime() - 7 * 1000 * 86400)
        }
    }
}, {
    $project: {
        _id: 1,
        numVotes: {
            $subtract: [{
                $size: "$votes.up"
            }, {
                $size: "$votes.down"
            }]
        }
    }
}, {
    $sort: {
        numVotes: -1
    }
}])
like image 80
David Rissato Cruz Avatar answered Oct 31 '25 12:10

David Rissato Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!