MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

unisci più documenti in un unico documento con entrambi i campi del documento in MongoDB

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"
  }
])

Risposta di @turivishal