对于多个原子更新,将update()与$set 一起使用。让我们创建一个包含文档的集合-
> db.demo699.insertOne({Name:"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6e370551299a9f98c93a7") } > db.demo699.insertOne({Name:"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6e37a551299a9f98c93a8") } > db.demo699.insertOne({Name:"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6e381551299a9f98c93a9") } > db.demo699.insertOne({Name:"John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6e38a551299a9f98c93aa") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo699.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea6e370551299a9f98c93a7"), "Name" : "Chris Brown" } { "_id" : ObjectId("5ea6e37a551299a9f98c93a8"), "Name" : "David Miller" } { "_id" : ObjectId("5ea6e381551299a9f98c93a9"), "Name" : "Chris Brown" } { "_id" : ObjectId("5ea6e38a551299a9f98c93aa"), "Name" : "John Doe" }
以下是使用MongoDB执行多个原子更新的查询-
> db.demo699.update({Name:"Chris Brown"},{ $set : { Name: "Adam Smith"} }, false, true ); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo699.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea6e370551299a9f98c93a7"), "Name" : "Adam Smith" } { "_id" : ObjectId("5ea6e37a551299a9f98c93a8"), "Name" : "David Miller" } { "_id" : ObjectId("5ea6e381551299a9f98c93a9"), "Name" : "Adam Smith" } { "_id" : ObjectId("5ea6e38a551299a9f98c93aa"), "Name" : "John Doe" }