Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by documents by week in mongodb

Tags:

mongodb

{
     "_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.

like image 891
Midhun Sudhakar Avatar asked Jan 05 '16 11:01

Midhun Sudhakar


People also ask

How is documents grouped in MongoDB?

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.

How can you group by a particular value in MongoDB?

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.

How do we display only first 5 documents of a collection using MongoDB?

To skip records in MongoDB, use skip(). With that, to display only a specific number of records, use limit().

How do I sort groups in MongoDB?

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.


1 Answers

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.

like image 133
Poorna Subhash Avatar answered Oct 24 '22 01:10

Poorna Subhash