I want to use group aggregation in mongoDB in order to group my documents based on their creation date. I didn't save the creation date as a field, but I know that I can extract this date from my ObjectId. So, I tried to write something like this:
db.sales.aggregate(
[
{
$group : {
_id : { month: {$month: ObjectId("$_id").getTimestamp()},
day: {$dayOfMonth: ObjectId("$_id").getTimestamp()},
year: {$year: ObjectId("$_id").getTimestamp()}
},
averageQuantity: { $avg: "$quantity" },
count: { $sum: 1 }
}
}
]
)
And I get this error: Error: invalid object id: length : @(shell):5:37
It works, when I write a special ObjectId instead of "$_id". For example: ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()
And it also works, when I have a date field in which I stored my creation dates and the write something like this:
db.sales.aggregate(
[
{
$group : {
_id : { month: {$month: "$date"},
day: {$dayOfMonth: "$date"},
year: {$year: "$date"}
},
averageQuantity: { $avg: "$quantity" },
count: { $sum: 1 }
}
}
]
)
But I want to know, how can I do it directly using my ObjectId and getting timestamps.
The group by aggregation and its related data is to be find on this link: https://docs.mongodb.com/manual/reference/operator/aggregation/group/
But I replaced the simple integer id s of this example, with my automatic mongoDB generated id s.