在 MongoDB 中更新特定陣列索引處物件?


要更新特定陣列索引處的物件,請在 MongoDB 中使用 update()。我們先建立一個帶有文件的集合 -

> db.updateObjectDemo.insertOne(
...   {
...       id : 101,
...       "StudentDetails":
...       [
...          [
...             {
...                "StudentName": "John"
...             },
...             { "StudentName": "Chris" }
...          ],
...          [ { "StudentName": "Carol" },
...          { "StudentName": "David" } ]
...       ]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccdcd9b685b30d09a7111e0")
}

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

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

這將產生以下輸出 -

{
   "_id" : ObjectId("5ccdcd9b685b30d09a7111e0"),
   "id" : 101,
   "StudentDetails" : [
      [
         {
            "StudentName" : "John"
         },
         {
            "StudentName" : "Chris"
         }
      ],
      [
         {
            "StudentName" : "Carol"
         },
         {
            "StudentName" : "David"
         }
      ]
   ]
}

以下是 MongoDB 中更新特定陣列索引處的物件的查詢 -

> db.updateObjectDemo.update({"id":101},{$set:{"StudentDetails.1.1.StudentName":"Mike"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

讓我們檢查一下特定索引 [1,1] 處的物件。值 “David” 已更新還是未更新 -

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

這將產生以下輸出 -

{
   "_id" : ObjectId("5ccdcd9b685b30d09a7111e0"),
   "id" : 101,
   "StudentDetails" : [
      [
         {
            "StudentName" : "John"
         },
         {
            "StudentName" : "Chris"
         }
      ],
      [
         {
            "StudentName" : "Carol"
         },
         {
            "StudentName" : "Mike"
         }
      ]
   ]
}

更新於:30-Jul-2019

542 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.