Gigi101
Gigi101

Reputation: 191

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

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.

Upvotes: 1

Views: 35

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

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

Upvotes: 1

Related Questions