簡體   English   中英

使用 MongoDB 聚合將兩個列表合並為一個 object

[英]Using MongoDB Aggregation to merge two lists into an object

我正在使用 mongoDB 並且我有類似於以下的文檔

{
  "files": ["Customers", "Items", "Contacts"],
  "counts": [1354, 892, 1542],
  ...
}

並使用聚合管道階段,我想將上述內容轉換為更像..

{
  "file_info": [
    {"file_name": "Customers", "record_counts": 1354},
    {"file_name": "Items", "record_counts": 892},
    {"file_name": "Contacts", "record_counts": 1542}
  ]
}

我嘗試過使用$map, $reduce, and $arrayToObject但沒有任何成功。 我可以使用哪些運算符從我當前所在的位置到達我需要的位置?

您可以使用$zip組合兩個 arrays 和$map以獲得新結構:

{
    $project: {
        file_info: {
            $map: {
                input: { $zip: { inputs: [ "$files", "$counts" ] } },
                in: {
                    file_name: { $arrayElemAt: [ "$$this", 0 ] },
                    record_counts: { $arrayElemAt: [ "$$this", 1 ] },
                }
            }
        }
    }
}

蒙戈游樂場

暫無
暫無

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

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