Home > Net >  How can I merge objects with the same key in an array in mongodb?
How can I merge objects with the same key in an array in mongodb?

Time:11-04

I derived the following data using the aggregate of mongodb.

{
    "first_count": 2,
    "second_count": 1,
    "third_count": 2,
    "test_count": 2,
    "sido": "대구",
    "guguns": [
        {
            "gugun": "남시",
            "first_count": 1,
            "second_count": 1,
            "third_count": 1
        },
        {
            "gugun": "부천군",
            "first_count": 1,
            "second_count": 0,
            "third_count": 1
        },
        {
            "gugun": "남시",
            "test_count": 1
        },
        {
            "gugun": "부천군",
            "test_count": 1
        }
    ]
}

This is the result of merging two facet data. But the result I want is:

{
    "first_count": 2,
    "second_count": 1,
    "third_count": 2,
    "test_count": 2,
    "sido": "대구",
    "guguns": [
        {
            "gugun": "남시",
            "first_count": 1,
            "second_count": 1,
            "third_count": 1,
            "test_count": 1
        },
        {
            "gugun": "부천군",
            "first_count": 1,
            "second_count": 0,
            "third_count": 1,
            "test_count": 1
        }
    ]
}

How does guguns.gugun combine the same values ​​into one? If possible, I would like to process it using mongodb aggregate.

CodePudding user response:

  • $unwind deconstruct the guguns array
  • $mergeObjects to merge current object of guguns with other
  • $group by _id and guguns.gugun property and get required fields first value and guguns merged object
  • $group by only _id and get required fields first value and construct the array of guguns object
db.collection.aggregate([
  { $unwind: "$guguns" },
  {
    $group: {
      _id: {
        _id: "$_id",
        gugun: "$guguns.gugun"
      },
      first_count: { $first: "$first_count" },
      second_count: { $first: "$second_count" },
      third_count: { $first: "$third_count" },
      test_count: { $first: "$test_count" },
      sido: { $first: "$sido" },
      guguns: { $mergeObjects: "$guguns" }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      first_count: { $first: "$first_count" },
      second_count: { $first: "$second_count" },
      third_count: { $first: "$third_count" },
      test_count: { $first: "$test_count" },
      sido: { $first: "$sido" },
      guguns: { $push: "$guguns" }
    }
  }
])

Playground

  • Related