对于聚合,请aggregate()
在MongoDB中使用。用$组将日期分组。让我们创建一个包含文档的集合-
> db.demo717.insertOne( ... { ... "shippingdetails": ... [ ... { ... duedate:"2020-04-29 22:33:04", ... }, ... { ... duedate:"2020-03-29 22:33:04", ... }, ... { ... duedate:"2020-04-29 22:33:04", ... }, ... { ... duedate:"2020-01-29 22:33:04", ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea9b3cd85324c2c98cc4c30") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo717.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ea9b3cd85324c2c98cc4c30"), "shippingdetails" : [ { "duedate" : "2020-04-29 22:33:04" }, { "duedate" : "2020-03-29 22:33:04" }, { "duedate" : "2020-04-29 22:33:04" }, { "duedate" : "2020-01-29 22:33:04" } ] }
以下是查询聚合以将嵌套文档(嵌套对象)中的日期分组-
> db.demo717.aggregate( ... { ... $unwind:"$shippingdetails"}, ... { ... $group: { ... _id: "$shippingdetails.duedate", ... count: { ... $sum: 1 ... } ... } ... } ... )
这将产生以下输出-
{ "_id" : "2020-01-29 22:33:04", "count" : 1 } { "_id" : "2020-03-29 22:33:04", "count" : 1 } { "_id" : "2020-04-29 22:33:04", "count" : 2 }