MongoDB add to joining collection field from base one

不羁的心 提交于 2019-11-28 14:32:57

You need to first $unwind the questions array and then need to apply $lookup and finally use $group to rollback again into the array.

db.games.aggregate([
  { "$unwind": "$questions" },
  { "$lookup": {
    "from": "questions",
    "localField": "questions.question_id",
    "foreignField": "_id",
    "as": "question_data"
  }},
  { "$unwind": "$question_data" },
  { "$addFields": {
    "question_data.position": "$questions.position",
    "question_data.question_id": "$questions.question_id"
  }},
  { "$group": {
    "_id": "$_id",
    "questions": { "$push": "$questions" },
    "question_data": { "$push": "$question_data" }
  }}
])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!