使用 MongoDB 壓縮兩個陣列並在重塑後建立新的物件陣列


為此,請使用聚合以及 $zip。zip 用於轉置陣列。我們建立一個帶有文件的集合 −

> db.demo339.insertOne({Id:101,Score1:["98","56"],Score2:[67,89]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e529ee5f8647eb59e5620a2")
}

在集合中顯示所有文件,藉助於 find() 方法 −

> db.demo339.find();

這將生成以下輸出 −

{ "_id" : ObjectId("5e529ee5f8647eb59e5620a2"), "Id" : 101, "Score1" : [ "98", "56" ], "Score2" : [ 67, 89 ] }

下面是使用 $zip 壓縮兩個陣列並在重塑後建立新的物件陣列的查詢 −

> db.demo339.aggregate([
...    {
...       "$project": {
...          "AllArrayObject": {
...             "$map": {
...                "input": {
...                   "$objectToArray": {
...                      "$arrayToObject": {
...                         "$zip": {
...                            "inputs": [
...                               "$Score1",
...                               "$Score2"
...                            ]
...                         }
...                      }
...                   }
...                },
.
...                "as": "el",
...                "in": {
...                   "Score1": "$$el.k",
...                   "Score2": "$$el.v"
...                }
...             }
...          }
...       }
...    }
... ])

這將生成以下輸出 −

{ "_id" : ObjectId("5e529ee5f8647eb59e5620a2"), "AllArrayObject" : [ { "Score1" : "98", "Score2" : 67 }, { "Score1" : "56", "Score2" : 89 } ] }

更新於:02-4-2020

172 個瀏覽量

開啟您的職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.