merge multiple documents into one document with both document fields in MongoDB

此生再无相见时 提交于 2021-01-29 08:48:37

问题


I have multiple documents In MobgoDB How to do to the group on "abc" and "xyz" and get one document. Please see the "Output Document". need to do the union with ( Document 1 U Document 2 ) and (Document 1 U Document 3) . U= Union

Document 1

{
    "data": {
      "Inside_data": {
        "project": {
          "abc": {
            "alpha": 4,
            "beta" : 45
          },
          "xyz": {
            "alpha": 214,
            "beta" : 431
          }
        }
      }
    }
}

Document 2

    "Deal": {
         "name": "abc",
         "url" : "www.abc.com,
         "email": [ "abc@gmail.com"],
         "total": 2
    }

Document 3

    "Deal": {
         "name": "xyz",
         "url" : "www.googl.com,
          "email": [ "xyz@gmail.com"],
          "total": 25
    }

Expected Output.

{
{
         "name": "abc",
         "url" : "www.abc.com,
          "email": "abc@gmail.com",
          "total": 2,
          "alpha": 4,
          "beta" : 45

    },
{
         "name": "xyz",
         "url" : "www.googl.com,
          "email": "xyz@gmail.com",
          "total": 25,
          "alpha": 214,
          "beta" : 431

    }
}

回答1:


db.collection.aggregate([
  {
    $match: {
      Deal: {
        $exists: true
      }
    }
  },
  {
    $lookup: {
      from: "collection",
      let: {
        name: "$Deal.name"
      },
      pipeline: [
        {
          $match: {
            data: {
              $exists: true
            }
          }
        },
        {
          $project: {
            data: {
              $reduce: {
                input: {
                  $objectToArray: "$data.Inside_data.project"
                },
                initialValue: {},
                in: {
                  $cond: [
                    {
                      $eq: [
                        "$$this.k",
                        "$$name"
                      ]
                    },
                    "$$this.v",
                    "$$value"
                  ]
                }
              }
            }
          }
        },
        {
          $project: {
            _id: 0,
            alpha: "$data.alpha",
            beta: "$data.beta"
          }
        }
      ],
      as: "Deal.data"
    }
  },
  {
    $unwind: "$Deal.data"
  }
])

Answer by @turivishal



来源:https://stackoverflow.com/questions/65778870/merge-multiple-documents-into-one-document-with-both-document-fields-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!