1

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.