簡體   English   中英

如何在 mongodb 的數組中合並具有相同鍵的對象?

[英]How can I merge objects with the same key in an array in mongodb?

我使用 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
        }
    ]
}

這是合並兩個方面數據的結果。 但我想要的結果是:

{
    "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
        }
    ]
}

guguns.gugun如何將相同的值合並為一個? 如果可能的話,我想使用 mongodb 聚合來處理它。

  • $unwind解構guguns數組
  • $mergeObjects合並的當前對象guguns與其他
  • $group by _idguguns.gugun屬性並獲取必填字段第一個值和guguns合並對象
  • $group by only _id並獲取必填字段的第一個值並構造guguns對象數組
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" }
    }
  }
])

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM