Erik Erik - 11 months ago 57
Node.js Question

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

I have

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, []}

Is it possible with MongoDB ?


Use the $max and $sum operators as

        "$group": {
            "_id": null,
            "count": { "$sum": 1 },
            "date": { "$max": "$date" }
]).exec(function (err, result) {