在 MongoDB 中按日期分组?
您可以使用聚合框架在 MongoDB 中按日期进行分组。让我们先创建一个包含部分文档的集合。用于创建包含文档的集合的查询如下
> db.groupByDateDemo.insertOne({"UserLoginDateTime":new ISODate()}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ee4df6fd07954a4890695") } > db.groupByDateDemo.insertOne({"UserLoginDateTime":new ISODate("2019-01-31 15:20:09.234Z")}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ee51c6fd07954a4890696") } > db.groupByDateDemo.insertOne({"UserLoginDateTime":new ISODate("2017-04-21 16:12:13.240Z")}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ee5336fd07954a4890697") } > db.groupByDateDemo.insertOne({"UserLoginDateTime":new ISODate("2016-05-25 19:11:21.130Z")}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ee54b6fd07954a4890698") } > db.groupByDateDemo.insertOne({"UserLoginDateTime":new ISODate("2016-05-25 19:11:21.130Z")}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ee8de6fd07954a4890699") } > db.groupByDateDemo.insertOne({"UserLoginDateTime":new ISODate()}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ee8e76fd07954a489069a") }
使用 find() 方法显示来自集合中的所有文档。查询如下
> db.groupByDateDemo.find().pretty();
输出如下
{ "_id" : ObjectId("5c6ee4df6fd07954a4890695"), "UserLoginDateTime" : ISODate("2019-02-21T17:50:23.076Z") } { "_id" : ObjectId("5c6ee51c6fd07954a4890696"), "UserLoginDateTime" : ISODate("2019-01-31T15:20:09.234Z") } { "_id" : ObjectId("5c6ee5336fd07954a4890697"), "UserLoginDateTime" : ISODate("2017-04-21T16:12:13.240Z") } { "_id" : ObjectId("5c6ee54b6fd07954a4890698"), "UserLoginDateTime" : ISODate("2016-05-25T19:11:21.130Z") } { "_id" : ObjectId("5c6ee8de6fd07954a4890699"), "UserLoginDateTime" : ISODate("2016-05-25T19:11:21.130Z") } { "_id" : ObjectId("5c6ee8e76fd07954a489069a"), "UserLoginDateTime" : ISODate("2019-02-21T18:07:35.208Z") }
以下是 MongoDB 中按日期分组的查询
> db.groupByDateDemo.aggregate([ ... { $group: { ... _id: { ... $add: [ ... { $dayOfYear: "$UserLoginDateTime"}, ... { $multiply: ... [400, {$year: "$UserLoginDateTime"}] ... } ... ]}, ... NumberOfTimes: { $sum: 1 }, ... f: {$min: "$UserLoginDateTime"} ... } ... }, ... { $sort: {_id: 1} }, ... { $limit: 10 }, ... { $project: { date: "$f", NumberOfTimes: 1, _id: 0} } ... ]);
输出如下
{ "NumberOfTimes" : 2, "date" : ISODate("2016-05-25T19:11:21.130Z") } { "NumberOfTimes" : 1, "date" : ISODate("2017-04-21T16:12:13.240Z") } { "NumberOfTimes" : 1, "date" : ISODate("2019-01-31T15:20:09.234Z") } { "NumberOfTimes" : 2, "date" : ISODate("2019-02-21T17:50:23.076Z") }
广告