在 MongoDB 中更新並防止覆蓋?
讓我們建立一個包含文件的集合 -
> db.demo601.insertOne( ... { ... id:1, ... userDetails: ... { ... userName:"John", ... userMailId:"John@gmail.com" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e95ff5ced011c280a0905c7") } > > db.demo601.insertOne( { id:2, userDetails: { userName:"Carol", userMailId:"Carol@gmail.com" } } );{ "acknowledged" : true, "insertedId" : ObjectId("5e95ff71ed011c280a0905c8") }
透過 find() 方法顯示集合中的所有文件 -
> db.demo601.find();
將生成以下輸出 -
{ "_id" : ObjectId("5e95ff5ced011c280a0905c7"), "id" : 1, "userDetails" : { "userName" : "John", "userMailId" : "John@gmail.com" } } { "_id" : ObjectId("5e95ff71ed011c280a0905c8"), "id" : 2, "userDetails" : { "userName" : "Carol", "userMailId" : "Carol@gmail.com" } }
以下是用於更新的查詢 -
>db.demo601.update({_id:ObjectId("5e95ff71ed011c280a0905c8")},{$set:{userMailId:"Carol@yahoo.com"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
透過 find() 方法顯示集合中的所有文件 -
> db.demo601.find();
將生成以下輸出 -
{ "_id" : ObjectId("5e95ff5ced011c280a0905c7"), "id" : 1, "userDetails" : { "userName" : "John", "userMailId" : "John@gmail.com" } } { "_id" : ObjectId("5e95ff71ed011c280a0905c8"), "id" : 2, "userDetails" : { "userName" : "Carol", "userMailId" : "Carol@gmail.com" }, "userMailId" : "Carol@yahoo.com" }
廣告