使用 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 } ] }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP