Home > database >  Combining arrays within an array in mongodb when said arrays have the same _id
Combining arrays within an array in mongodb when said arrays have the same _id

Time:05-24

I'm working on a project using mongodb, and within an array I am currently getting two arrays with the same _id. I would like these two sets of data to be combined. What I am currently am getting:

    "items": [
      {
        "_id": "Red",
        "15-17": 1
      },
      {
        "_id": "Bliss",
        "15-17": 2
      },
      {
        "_id": "Green",
        "18-25": 1
      },
      {
        "_id": "Bliss",
        "18-25": 2
      }
    ]

What I would like to get:

   "items": [
      {
        "_id": "Red",
        "15-17": 1
      },
      {
        "_id": "Bliss",
        "15-17": 2,
        "18-25": 2
      },
      {
        "_id": "Green",
        "18-25": 1
      },
    ]

I would really appreciate any help or advice on how to do this.

CodePudding user response:

You can achieve this in several different ways, here is what i believe to be the simplest solution.

We will unwind the items array, then group for each item._id, this will allow us to "merge" all the values from the various values.

Eventually we will restore the original structure, like so:

db.collection.aggregate([
  {
    $unwind: "$items"
  },
  {
    $group: {
      _id: "$items._id",
      values: {
        $push: "$items"
      },
      id: {
        $first: "$_id"
      }
    }
  },
  {
    $addFields: {
      values: {
        $reduce: {
          input: "$values",
          initialValue: {},
          in: {
            "$mergeObjects": [
              "$$this",
              "$$value"
            ]
          }
        }
      }
    }
  },
  {
    $group: {
      _id: "$id",
      items: {
        $push: "$values"
      }
    }
  }
])

Mongo Playground

  • Related