Mongo DB + group by with last field data

时间:2017-01-05 09:49:44

标签: node.js mongodb mongodb-query aggregation-framework

我在集合中有示例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")
}]

我需要检索以下条件的数据。

  1. 按用户名分组。
  2. 用户名不等于“zzz”
  3. 按日期排序desc order。
  4. 还需要日期字段(具有最新/最后记录)。
  5. 得到总数。
  6. 期待输出:

    [{
        "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 }
        }}])
    

1 个答案:

答案 0 :(得分:2)

试试这个:

    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")
}

在线试用:mongoplayground.net/p/3_-s2tUjPFi