更新

更新整個物件:

db.people.update({name: 'Tom'}, {age: 29, name: 'Tom'})

// New in MongoDB 3.2
db.people.updateOne({name: 'Tom'},{age: 29, name: 'Tom'}) //Will replace only first matching document.

db.people.updateMany({name: 'Tom'},{age: 29, name: 'Tom'}) //Will replace all matching documents.

或者只更新文件的單個欄位。在這種情況下 age

db.people.update({name: 'Tom'}, {$set: {age: 29}})

你還可以通過新增第三個引數來同時更新多個文件。此查詢將更新名稱等於 Tom 的所有文件:

db.people.update({name: 'Tom'}, {$set: {age: 29}}, {multi: true})

// New in MongoDB 3.2
db.people.updateOne({name: 'Tom'},{$set:{age: 30}) //Will update only first matching document.

db.people.updateMany({name: 'Tom'},{$set:{age: 30}}) //Will update all matching documents.

如果要更新新欄位,該欄位將新增到文件中。

db.people.updateMany({name: 'Tom'},{$set:{age: 30, salary:50000}})// Document will have `salary` field as well.

如果需要更換檔案,

db.collection.replaceOne({name:'Tom'}, {name:'Lakmal',age:25,address:'Sri Lanka'})

可以使用。

注意 :用於標識物件的欄位將儲存在更新的文件中。未在更新部分中定義的欄位將從文件中刪除。