Mongo DB +与最后一个字段的数据
我有collections中的示例json数据。
样本数据:
[{ "_id" : 1, "username" : "abcd", "createdDate" : ISODate("2016-06-03T08:52:32.434Z") }, { "_id" : 2, "username" : "abcd", "createdDate" : ISODate("2016-05-03T09:52:32.434Z") }, { "_id" : 3, "username" : "abcd", "createdDate" : ISODate("2016-04-03T10:52:32.434Z") }, { "_id" : 4, "username" : "xyz", "createdDate" : ISODate("2016-03-03T10:52:32.434Z") },{ "_id" : 5, "username" : "xyz", "createdDate" : ISODate("2016-02-03T10:52:32.434Z") },{ "_id" : 6, "username" : "zzz", "createdDate" : ISODate("2016-01-03T10:52:32.434Z") }]
这些数据我需要检索以下条件的数据。
- 按用户名分组。
- 用户名不等于“zzz”
- 按datesorting。
- 需要date字段(最新/最后一个logging)。
- 得到总数。
期待输出:
[{ "username" : "abcd", "createdDate" : "2016-06-03T08:52:32.434Z", "total" : 3 }, { "username" : "xyz", "createdDate" : "2016-03-03T10:52:32.434Z", "total" : 2 }]
查询:
db.logs.aggregate([ { "$match": { "username": { "$ne": "zzz" } }}, { "$group": { "_id": { "username": "$username", "createdDate": "$createdDate" }, "count": { "$sum": 1 } }}])
尝试这个 :
db.logs.aggregate([ { "$match":{ "username":{ "$ne":"zzz" } } }, { "$group":{ _id:"$username", "count":{ "$sum":1 }, date:{ $max:"$createdDate" } } }, { $project:{ username:"$_id", total:"$count", createdDate:"$date" } } ])
产量
{ "_id":"xyz", "username":"xyz", "total":2, "createdDate": ISODate("2016-03-03T10:52:32.434 Z") }{ "_id":"abcd", "username":"abcd", "total":3, "createdDate": ISODate("2016-06-03T08:52:32.434 Z") }