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

zul*_*kha 0 mongodb aggregation-framework

我有两个模式usersLessons。我必须按每个用户获取课程组。我还将用户的参考 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"
      }
    }
  }
}])
Run Code Online (Sandbox Code Playgroud)

从上面的查询我能够得到如下的输出,

{
    "_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")
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

现在我想将_id重命名为user是否可以在聚合管道中实现这一点?

Dip*_*mar 5

我们可以这样做$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',
  }
}
])
Run Code Online (Sandbox Code Playgroud)

我知道,我发布答案太晚了,但如果将来有人来这里,这可能对他们有帮助。