我们如何重命名mongodb中groupby查询返回的_id字段

时间:2017-05-31 08:48:32

标签: mongodb aggregation-framework

我有两个模式用户课程。我必须每个用户获取课程组。此外,我还在课程架构中存储用户的参考ID。

要获得结果,我已采用以下格式进行聚合查询

db.lessons.aggregate([{
  $lookup: {
    from: "users",
    localField: "user",
    foreignField: "_id",
    as: "user"
  }
}, {
  "$project": {
    "user": "$user.email",
    "title": "$title",
    "scheduled_at": "$scheduled_at"
  }
}, {
  $group: {
    _id: "$user",
    num_lessons: {
      $sum: 1
    },
    lessons: {
      $push: {
        title: "$title",
        schedule: "$scheduled_at"
      }
    }
  }
}])

从上面的查询中我可以得到如下输出

{
    "_id" : [ 
        "harry.quill@gmail.com"
    ],
    "num_lessons" : 1.0,
    "lessons" : [ 
        {
            "title" : "welcome to Mongoose",
            "schedule" : {
                "endTime" : ISODate("2017-06-12T08:30:00.000Z"),
                "startTime" : ISODate("2017-06-10T04:00:00.000Z")
            }
        }
    ]
}


{
    "_id" : [ 
        "tom.quill@gmail.com"
    ],
    "num_lessons" : 1.0,
    "lessons" : [ 
        {
            "title" : "welcome to Angularjs",
            "schedule" : {
                "endTime" : ISODate("2017-05-31T09:30:00.000Z"),
                "startTime" : ISODate("2017-05-21T04:00:00.000Z")
            }
        }
    ]
}

现在我想将 _id 重命名为用户。是否有可能在聚合管道中实现这一目标?

1 个答案:

答案 0 :(得分:1)

我们可以通过$project

db.lessons.aggregate([{
  $lookup: {
    from: "users",
    localField: "user",
    foreignField: "_id",
    as: "user"
  }
}, {
  "$project": {
    "user": "$user.email",
    "title": "$title",
    "scheduled_at": "$scheduled_at"
  }
}, {
  $group: {
    _id: "$user",
    num_lessons: {
      $sum: 1
    },
    lessons: {
      $push: {
        title: "$title",
        schedule: "$scheduled_at"
      }
    }
  }
},
{
  $project: {
    _id: 0,
    user: "$_id",
    num_lessons: '$num_lessons',
    lessons: '$lessons',
  }
}
])

我知道,我发布答案为时已晚,但如果将来有人来这里,可能会对他们有所帮助。