透過 MongoDB 集合中的 ID 搜尋陣列條目並執行更新


要透過 id 搜尋陣列,請使用位置 $ 運算子。對於更新,請在 MongoDB 中使用 UPDATE。讓我們建立一個包含以下文件的集合 -

> db.demo49.insertOne(
... {
...
...    "Name": "David",
...    "Details": [
...       {
...          "_id": "D1234",
...          "Subject":"MySQL"
...       },
...       {
...          "_id": "E234",
...          "Subject":"Java"
...       },
...       {
...          "_id": "F456",
...          "Subject":"Python"
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e270a77cfb11e5c34d89902")
}

在 find() 方法的幫助下顯示某個集合中的所有文件 -

> db.demo49.find();

將產生以下輸出 -

{ "_id" : ObjectId("5e270a77cfb11e5c34d89902"), "Name" : "David", "Details" : [ { "_id" : "D1234", "Subject" : "MySQL" }, { "_id" : "E234", "Subject" : "Java" }, { "_id" : "F456", "Subject" : "Python" } ] }

以下是透過 id 在 MongoDB 集合中搜索陣列條目的查詢 -

> db.demo49.update( {"Details._id":"E234"},
... {$set:{"Details.$.Subject":"MongoDB"}}, false, true )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

在 find() 方法的幫助下顯示某個集合中的所有文件 -

> db.demo49.find();

將產生以下輸出 -

{ "_id" : ObjectId("5e270a77cfb11e5c34d89902"), "Name" : "David", "Details" : [ { "_id" : "D1234", "Subject" : "MySQL" }, { "_id" : "E234", "Subject" : "MongoDB" }, { "_id" : "F456", "Subject" : "Python" } ] }

更新時間: 2020-04-03

86 次瀏覽

開啟您的 職業生涯

完成該課程獲得認證

開始
廣告
© . All rights reserved.