要按日期分组,请在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" } ] }