根据MongoDB中的日期范围按日/月/周分组
要进行分组,请在MongoDB中使用$week和$month。让我们创建一个包含文档的集合-
> db.demo133.insertOne({"Rank":18,"DueDate":new ISODate("2020-01-10")}); { "acknowledged" : true, "insertedId" : ObjectId("5e31980968e7f832db1a7f78") } > db.demo133.insertOne({"Rank":12,"DueDate":new ISODate("2020-01-10")}); { "acknowledged" : true, "insertedId" : ObjectId("5e31982568e7f832db1a7f79") } > db.demo133.insertOne({"Rank":12,"DueDate":new ISODate("2020-02-01")}); { "acknowledged" : true, "insertedId" : ObjectId("5e31986568e7f832db1a7f7a") } > db.demo133.insertOne({"Rank":20,"DueDate":new ISODate("2020-02-01")}); { "acknowledged" : true, "insertedId" : ObjectId("5e31986c68e7f832db1a7f7b") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo133.find();
这将产生以下输出-
{ "_id" : ObjectId("5e31980968e7f832db1a7f78"), "Rank" : 18, "DueDate" : ISODate("2020-01-10T00:00:00Z") } { "_id" : ObjectId("5e31982568e7f832db1a7f79"), "Rank" : 12, "DueDate" : ISODate("2020-01-10T00:00:00Z") } { "_id" : ObjectId("5e31986568e7f832db1a7f7a"), "Rank" : 12, "DueDate" : ISODate("2020-02-01T00:00:00Z") } { "_id" : ObjectId("5e31986c68e7f832db1a7f7b"), "Rank" : 20, "DueDate" : ISODate("2020-02-01T00:00:00Z") }
以下是根据日期范围按天/月/周分组的查询-
> db.demo133.aggregate([ ... { ... "$project": { ... "DueDateWeek": { "$week": "$DueDate" }, ... "DueDateMonth": { "$month": "$DueDate" }, ... "Rank": 1 ... } ... }, ... { ... "$group": { ... "_id": "$DueDateWeek", ... "AvgValue": { "$avg": "$Rank" }, ... "MonthValue": { "$first": "$DueDateMonth" } ... } ... } ... ])
这将产生以下输出-
{ "_id" : 4, "AvgValue" : 16, "MonthValue" : 2 } { "_id" : 1, "AvgValue" : 15, "MonthValue" : 1 }