用於更新巢狀文件的 MongoDB 查詢


讓我們建立一個包含文件的集合 -

> db.demo595.insertOne( { "Information": [
   { "_id": new ObjectId(), Name:"Chris" },
   { _id:new ObjectId(), Name:"Robert" }
] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e93369cfd2d90c177b5bce4")
}

利用 find() 方法顯示集合中的所有文件 -

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

這將產生以下輸出 -

{
   "_id" : ObjectId("5e93369cfd2d90c177b5bce4"),
   "Information" : [
      {
         "_id" : ObjectId("5e93369cfd2d90c177b5bce2"),
         "Name" : "Chris"
      },
      {
         "_id" : ObjectId("5e93369cfd2d90c177b5bce3"),
         "Name" : "Robert"
      }
   ]
}

以下是更新巢狀文件的查詢 -

>db.demo595.update({"Information._id":ObjectId("5e93369cfd2d90c177b5bce2")},
   {$set:{"Info rmation.$.Name":"David Miller"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

利用 find() 方法顯示集合中的所有文件 -

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

這將產生以下輸出 -

{
   "_id" : ObjectId("5e93369cfd2d90c177b5bce4"),
   "Information" : [
      {
         "_id" : ObjectId("5e93369cfd2d90c177b5bce2"),
         "Name" : "David Miller"
      },
      {
         "_id" : ObjectId("5e93369cfd2d90c177b5bce3"),
         "Name" : "Robert"
      }
   ]
}

更新於:15-5-2020

2 千次瀏覽

啟動您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.