{
"_id" : ObjectId("568b650543712795bf864a45"),
"companyId" : "55e2d7cfdc8f74d14f5c900f",
"timeStamp" : ISODate("2014-12-03T18:30:00.000Z")
},
{
"_id" : ObjectId("568b650543712795bf864a49"),
"companyId" : "55e2d7cfdc8f74d14f5c900f",
"timeStamp" : ISODate("2014-12-04T18:30:00.000Z")
}
how to group by documents by week in mongodb. i need to get document grouped by last 7 weeks and week grouping should be on the basis of "timeStamp" field in the document.
The $group stage separates documents into groups according to a "group key". The output is one document for each unique group key. A group key is often a field, or group of fields. The group key can also be the result of an expression.
We can group by single as well as multiple field from the collection, we can use $group operator in MongoDB to group fields from the collection and returns the new document as result. We are using $avg, $sum, $max, $min, $push, $last, $first and $addToSet operator with group by in MongoDB.
To skip records in MongoDB, use skip(). With that, to display only a specific number of records, use limit().
And for group sorting in MongoDB, the $group operator is used with the $sort operator. With the help of the $group and $sort operator, MongoDB can also sort the grouped data in ascending or descending order. In this post, we have provided an informative insight into the aggregate group sort functionality of MongoDB.
You can achieve this by using the aggregate operation. There is $week aggregation operation in mongodb.
First determine the startDate using whatever programming language you use.
In following pipeline operation, counting the number of documents matching a week. You may do it on any field/type of aggregation you needed.
pipeline = [
{
$match: {
timeStamp: {$gt: ISODate(startDate)},
}
},
{
$group: {
_id: {$week: '$timeStamp'},
documentCount: {$sum: 1}
}
}
];
db.mycollection.aggregate(pipeline)
For the above two documents you specified the result will be
{ "_id" : 48, "documentCount" : 2 }
The _id
above says, 48th week, and there are two documents.
Go through the link $week to know how mongodb counts the week numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With