更新

更新整个对象:

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'})

可以使用。

注意 :用于标识对象的字段将保存在更新的文档中。未在更新部分中定义的字段将从文档中删除。