簡體   English   中英

如何將 mongo db 中的不同項目聚合到單獨的數組中?

[英]How to aggregate distinct items in mongo db to separate array?

我有一個 API 端點,它檢查 mongo db 並以以下結構返回,例如:

{
  "Name": "Test"
  "Location": "Whatever",
  "customerServices": [
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "West",
        "name": "test"
      },
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "West",
        "name": "test"
      },
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "East",
        "name": "test"
      }
  ]
}

我想要做的是將聚合添加到管道中,這將創建額外的 field-serviceCounties並包含來自 customerServices 數組的不同serviceCounty 值。 如下所示:

{
  "Name": "Test"
  "Location": "Whatever",
  "customerServices": [
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "West",
        "name": "test"
      },
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "West",
        "name": "test"
      },
      {
        "id": "test",
        "cusId": "test",
        "serviceAdr": "test",
        "serviceCounty": "East",
        "name": "test"
      }
  ],
  "serviceCounties": [
    {
      "countyName":"East"
    },
    {
      "countyName":"West"
    }
] 
}

我嘗試了以下方法,但沒有奏效。 我缺少一些東西或做錯了:

                'serviceCounties': {
                    '$reduce': {
                        'input': '$services.event.services',
                        'initialValue': [],
                        'in': [{
                            "countyName": { '$concatArrays': ["$$value.serviceCounty", "$$this"] }
                        }]
                    }
                }

任何想法如何做到這一點?

你可以試試這個。

db.collection.aggregate([
  {
    $addFields: {
      "serviceCounties": [
        {
          $map: {
            input: "$customerServices",
            in: {
              "countyName": "$$this.serviceCounty"
            }
          }
        }
      ]
    }
  }
])

操場

$addfields添加serviceCounties數組
$map以獲取customerServices值。

暫無
暫無

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

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