按 MongoDB 集合中的日期分组?
要按日期分组,请在 MongoDB 聚合中使用 $group。我们创建一个带文档的集合 −
> db.demo657.insertOne({ ... id: 1, ... Name: "Chris", ... DueDate: new ISODate("2020-04-22") ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea064b44deddd72997713d6") } > db.demo657.insertOne( ... { ... id: 1, ... Name: "John", ... DueDate: new ISODate("2020-04-22") ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5ea064b44deddd72997713d7") } > db.demo657.insertOne( ... { ... id: 1, ... Name: "Chris", ... DueDate: new ISODate("2020-04-22") ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5ea064b44deddd72997713d8") }
借助 find() 方法显示集合中的所有文档 −
> db.demo657.find();
这将产生以下输出 −
{ "_id" : ObjectId("5ea064b44deddd72997713d6"), "id" : 1, "Name" : "Chris", "DueDate" : ISODate("2020-04-22T00:00:00Z") } { "_id" : ObjectId("5ea064b44deddd72997713d7"), "id" : 1, "Name" : "John", "DueDate" : ISODate("2020-04-22T00:00:00Z") } { "_id" : ObjectId("5ea064b44deddd72997713d8"), "id" : 1, "Name" : "Chris", "DueDate" : ISODate("2020-04-22T00:00:00Z") }
以下是按 MongoDB 集合中的日期分组的查询 −
> db.demo657.aggregate([ ... {$match: {id:1, DueDate: {$gte:new ISODate('2020-04-21'), $lt:new ISODate ("2020-04-23")}}}, ... {$project: ... {day: {'$dayOfMonth': '$DueDate'},month: {'$month':'$DueDate'},year: {'$year':'$DueDate'},Name:"$Name" } ... }, ... {$group: { ... _id: {day:'$day',month:'$month',year:'$year'}, ... ListOfNames: {$push:{Name:'$Name'}} ... }} ... ])
这将产生以下输出 −
{ "_id" : { "day" : 22, "month" : 4, "year" : 2020 }, "ListOfNames" : [ { "Name" : "Chris" }, { "Name" : "John" }, { "Name" : "Chris" } ] }
广告