1

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.

1 Answer 1

3
  • $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

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.