How can I group my MongoDB collection based on the creation date which I extract form objectId? How can I group my MongoDB collection based on the creation date which I extract form objectId? mongodb mongodb

How can I group my MongoDB collection based on the creation date which I extract form objectId?


getTimestamp() is a function and it should be used within a javascript function.

Two things you need to correct in the query. One is the retrieval of Id and other one is using getTimestamp() function.

Retrieval of Id

_id : { month: {$month: ObjectId("$_id").getTimestamp()},                    day: {$dayOfMonth: ObjectId("$_id").getTimestamp()},                    year: {$year: ObjectId("$_id").getTimestamp()}      }

Correct way of retrieving id with month, day and year

_id : { month: "$_id.month",  day: "$_id.day", year: "$_id.year"},

Reason:

month is part of the document id and hence it has to be retrieved this way. similarly the day and year.

Getting the Timestamp

Put the result into a javascript loop and use the getTimestamp() method.

db.sales.aggregate(   [      {        $group : {           _id : { month: "$_id.month",  day: "$_id.day", year: "$_id.year"},           averageQuantity: { $avg: "$quantity" },           count: { $sum: 1 }        }      }   ]).forEach(function (doc)     {     doc["doc._id.month"]=doc._id.month.getTimestamp();     doc["doc._id.day"]=doc._id.day.getTimestamp();     doc["doc._id.year"]=doc._id.year.getTimestamp();     printjson(doc);    });

If you have a collection like this

{        "_id" : {                "month" : ObjectId("57bd7d3c0da65e3f92328e50"),                "day" : ObjectId("57bd7d3c0da65e3f92328e51"),                "year" : ObjectId("57bd7d3c0da65e3f92328e52")        },        "quantity" : 200}

and the result after executing aggregate query with javascript function would give the following result

{        "_id" : {                "month" : ObjectId("57bd7d3c0da65e3f92328e50"),                "day" : ObjectId("57bd7d3c0da65e3f92328e51"),                "year" : ObjectId("57bd7d3c0da65e3f92328e52")        },        "averageQuantity" : 200,        "count" : 1,        "doc._id.month" : ISODate("2016-08-24T10:55:56Z"),        "doc._id.day" : ISODate("2016-08-24T10:55:56Z"),        "doc._id.year" : ISODate("2016-08-24T10:55:56Z")}