结合$ project,$ unwind&的查询$组

时间:2016-07-11 04:29:17

标签: mongodb aggregation-framework

我有以下数据集:

{
  "_id" : ObjectId("57684f2b61f2af6d49fa6dbd"),
  "firstname" : "First1",
  "surname" : "Sur1",
  "email" : "first1@sur1.com",
  "goals" : [ 
    {
        "gId" : "base1",
        "recordDate" : ISODate("2016-06-21T20:05:48.972Z")
    }, 
    {
        "gId" : "base2",
        "recordDate" : ISODate("2016-06-21T20:05:48.972Z")

    }, 
    {
        "gId" : "base1",
        "recordDate" : ISODate("2016-06-21T20:05:48.972Z")

    }
 ]
}

我需要以下结果:

{
  "_id" : ObjectId("57684f2b61f2af6d49fa6dbd"),
  "firstname" : "First1",
  "surname" : "Sur1",
  "email" : "first1@sur1.com",
  "goals" : [
    {
       "gId" : "base1",
       "count" : 2
    },
    {
       "gId" : "base2",
       "count" : 1
    }
  ]
}

到目前为止,我一直在使用聚合查询,但我无法找到解决问题的方法。我的查询看起来像这样,但它不起作用。第一位$project可以自行运行,$unwind$group也可以运行,但我不知道如何将它们组合在一起。

db.getCollection('users').aggregate(
{
  $project : {
    firstname: "$firstname",
    surname: "$surname",
    email: "$email",
    goals: "$goals"
  }
},
{ 
  $unwind: '$goals' 
},
{ 
  $group: {
    gid: '$goals.gId',
    count: {'$sum': 1}
  }
}
)

提前致谢, 汤姆

1 个答案:

答案 0 :(得分:3)

使用以下管道尝试

db.getCollection('users').aggregate(
    { 
      $unwind: '$goals' 
    },
    { 
      $group: {
        _id: {
            firstname: "$firstname",
            surname: "$surname",
            email: "$email",
            gId: "$goals.gId"
        },
        count: {'$sum': 1}
      }
    },
    {
        $group: {
            _id: {
                firstname: "$_id.firstname",
                surname: "$_id.surname",
                email: "$_id.email"
            },
            goals: {
                $push: {
                    gId: "$_id.gId",
                    count: "$count"
                }
            }        
        }
    },
    {
        $project: {
            _id: 0,
            firstname: "$_id.firstname",
            surname: "$_id.surname",
            email: "$_id.email",
            goals: 1
        }
    }
)

结果如下所示

{
    "goals" : [ 
        {
            "gId" : "base2",
            "count" : 1.0
        }, 
        {
            "gId" : "base1",
            "count" : 2.0
        }
    ],
    "firstname" : "First1",
    "surname" : "Sur1",
    "email" : "first1@sur1.com"
}