如何透過一個更新呼叫來更新 MongoDB 中的兩個獨立陣列?


你可以使用 $push 運算子來實現。我們先建立一個帶有文件的集合

>db.twoSeparateArraysDemo.insertOne({"StudentName":"Larry","StudentFirstGameScore":[98],"StudentSecondGameScore":[77]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b152815e86fd1496b38b8")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"Mike","StudentFirstGameScore":[58],"StudentSecondGameScore":[78]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b152d15e86fd1496b38b9")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"David","StudentFirstGameScore":[65],"StudentSecondGameScore":[67]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9b153315e86fd1496b38ba")
}

以下是利用 find() 方法來顯示集合中所有文件的查詢

> db.twoSeparateArraysDemo.find().pretty();

這將產生以下輸出

{
   "_id" : ObjectId("5c9b152815e86fd1496b38b8"),
   "StudentName" : "Larry",
   "StudentFirstGameScore" : [
      98
   ],
   "StudentSecondGameScore" : [
      77
   ]
}
{
   "_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
   "StudentName" : "Mike",
   "StudentFirstGameScore" : [
      58
   ],
   "StudentSecondGameScore" : [
      78
   ]
}
{
   "_id" : ObjectId("5c9b153315e86fd1496b38ba"),
   "StudentName" : "David",
   "StudentFirstGameScore" : [
      65
   ],
   "StudentSecondGameScore" : [
      67
   ]
}

以下是透過一個更新呼叫在 MongoDB 中同時推送兩個獨立陣列的查詢

> db.twoSeparateArraysDemo.update({_id:ObjectId("5c9b152d15e86fd1496b38b9")}, { $push : {
   StudentFirstGameScore : 45, StudentSecondGameScore : 99}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

讓我們檢查一下值是否推送到兩個獨立的陣列中

> db.twoSeparateArraysDemo.find().pretty();

這將產生以下輸出

{
   "_id" : ObjectId("5c9b152815e86fd1496b38b8"),
   "StudentName" : "Larry",
   "StudentFirstGameScore" : [
      98
   ],
   "StudentSecondGameScore" : [
      77
   ]
}
{
   "_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
   "StudentName" : "Mike",
   "StudentFirstGameScore" : [
      58,
      45
   ],
   "StudentSecondGameScore" : [
      78,
      99
   ]
}
{
   "_id" : ObjectId("5c9b153315e86fd1496b38ba"),
   "StudentName" : "David",
   "StudentFirstGameScore" : [
      65
   ],
   "StudentSecondGameScore" : [
      67
   ]
}

更新於: 30-7-2019

105 次瀏覽

開啟你的 職業

獲取認證證書,完成課程

開始
廣告
© . All rights reserved.