Grouping by day / month / week by date range

This refers to this question .

This is my dataset:

[ { "rating": 4, "ceatedAt": ISODate("2016-08-08T15:32:41.262+0000") }, { "rating": 3, "createdAt": ISODate("2016-08-08T15:32:41.262+0000") }, { "rating": 3, "ceatedAt": ISODate("2016-07-01T15:32:41.262+0000") }, { "rating": 5, "createdAt": ISODate("2016-07-01T15:32:41.262+0000") } ] 

I want to be able to filter the database by week or month in a date range.

How can I do this in mongo?

This was the answer given to group by day.

 db.collection.aggregate([ { "$project": { "formattedDate": { "$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" } }, "createdAtMonth": { "$month": "$ceatedAt" }, "rating": 1 } }, { "$group": { "_id": "$formattedDate", "average": { "$avg": "$rating" }, "month": { "$first": "$createdAtMonth" }, } } ]) 
0
source share
1 answer

To group, run the following pipeline weekly, which mainly uses Date Aggregation Operators to retrieve parts of the date:

 db.collection.aggregate([ { "$project": { "createdAtWeek": { "$week": "$createdAt" }, "createdAtMonth": { "$month": "$createdAt" }, "rating": 1 } }, { "$group": { "_id": "$createdAtWeek", "average": { "$avg": "$rating" }, "month": { "$first": "$createdAtMonth" } } } ]) 

and for monthly aggregates, replace the $group key to use the created field of the month:

 db.collection.aggregate([ { "$project": { "createdAtWeek": { "$week": "$createdAt" }, "createdAtMonth": { "$month": "$createdAt" }, "rating": 1 } }, { "$group": { "_id": "$createdAtMonth", "average": { "$avg": "$rating" }, "week": { "$first": "$createdAtWeek" } } } ]) 
+1
source

All Articles