Midhun Sudhakar
Midhun Sudhakar

Reputation: 1328

How to group by documents by week in 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.

Upvotes: 11

Views: 16927

Answers (1)

Poorna Subhash
Poorna Subhash

Reputation: 2128

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.

Upvotes: 21

Related Questions