Erik Erik - 6 months ago 26
Node.js Question

How to get count and max date with single query in MongoDB?

I have

Post
collection as like as following:

{ "_id" : ObjectId(..), "date" : ISODate("2014-03-01T08:00:00Z") }
{ "_id" : ObjectId(..), "date" : ISODate("2014-03-01T09:00:00Z") }
{ "_id" : ObjectId(..), "date" : ISODate("2014-03-15T09:00:00Z") }
{ "_id" : ObjectId(..), "date" : ISODate("2014-04-04T11:21:39.736Z") }
{ "_id" : ObjectId(..), "date" : ISODate("2014-04-04T21:23:13.331Z") }


I need to get total count and max date of post. So desired result for coeumtns above is the following:

{count: 5, date: ISODate("2014-04-04T21:23:13.331Z")}


How to get desired result with single query to MongoDB without handling and counting in application code?

@chridam thanks for the response. I've accepted your answer as best one! Could help me with one more thing?

Let's say that posts are not exists yet, so I need to fetch result with zero count and current date as timestamp like the following:

{count: 0, [Date.now()]}


Is it possible with MongoDB ?

Answer

Use the $max and $sum operators as

Model.aggregate([ 
    {
        "$group": {
            "_id": null,
            "count": { "$sum": 1 },
            "date": { "$max": "$date" }
        }
    }
]).exec(function (err, result) {
   console.log(result);
})
Comments