Mongo汇总集合和项目字段

时间:2020-03-12 07:03:03

标签: mongodb mongodb-query

我有2个收藏集。

集合1模型:

{
    "_id" : "abcdefgh",
    "questionType" : "multiselect",
    "question" : "how do you feel",
    "options" : [
        {
            "option" : "Good ",
            "additionalTextRequired" : false
        },
        {
            "option" : "Bad",
            "additionalTextRequired" : false
        }
    ],
    "active" : false,
}

集合2模型:

{
    "_id" : "bhanu",
    "someunrelatedfield":"dasf",
    "responses" : [
        {
            "questionId" : "abcdefgh",
            "response" : [
                "Good"
            ],
            "valid" : true,
            "unrelatedfield":"dontprojectthese",
        },
        {
            "questionId" : "someotherid",
            "response" : [
                "cool"
            ],
            "valid" : true,
        }
    ],
}

我想在查询后得到以下结果,

{
    "_id":"bhanu",
    "responses":[
        {
             "question": "how do you feel",
             "response": [
                    "good"
               ]
              "valid":true,
       }
    ]
}

基本上,我想在集合2和项目指定的字段中将“ questionId”替换为“ question”。 我该如何编写查询?

1 个答案:

答案 0 :(得分:1)

您需要像这样的$lookup运算符执行MongoDB aggregation

db.collection2.aggregate([
  {
    $lookup: {
      from: "collection1",
      localField: "responses.questionId",
      foreignField: "_id",
      as: "tmp"
    }
  },
  {
    $addFields: {
      responses: {
        $map: {
          input: "$responses",
          as: "response",
          in: {
            $mergeObjects: [
              "$$response",
              {
                $arrayElemAt: [
                  {
                    $filter: {
                      input: "$tmp",
                      cond: {
                        $eq: [
                          "$$response.questionId",
                          "$$this._id"
                        ]
                      }
                    }
                  },
                  0
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $unset: [
      "responses.questionId"
      //put here all fields to be removed
    ]
  }
])

MongoPlayground