您需要使用multi:true来更新多个文档。首先让我们创建一个包含文档的集合-
> db.multiUpdateDemo.insertOne({"ClientName":"John","ClientAge":29}); { "acknowledged" : true, "insertedId" : ObjectId("5cda5bc0b50a6c6dd317adc8") } > db.multiUpdateDemo.insertOne({"ClientName":"Carol","ClientAge":31}); { "acknowledged" : true, "insertedId" : ObjectId("5cda5bc1b50a6c6dd317adc9") } > db.multiUpdateDemo.insertOne({"ClientName":"John","ClientAge":39}); { "acknowledged" : true, "insertedId" : ObjectId("5cda5bc3b50a6c6dd317adca") } > db.multiUpdateDemo.insertOne({"ClientName":"John","ClientAge":41}); { "acknowledged" : true, "insertedId" : ObjectId("5cda5bc5b50a6c6dd317adcb") } > db.multiUpdateDemo.insertOne({"ClientName":"David","ClientAge":35}); { "acknowledged" : true, "insertedId" : ObjectId("5cda5bc6b50a6c6dd317adcc") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.multiUpdateDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cda5bc0b50a6c6dd317adc8"), "ClientName" : "John", "ClientAge" : 29 } { "_id" : ObjectId("5cda5bc1b50a6c6dd317adc9"), "ClientName" : "Carol", "ClientAge" : 31 } { "_id" : ObjectId("5cda5bc3b50a6c6dd317adca"), "ClientName" : "John", "ClientAge" : 39 } { "_id" : ObjectId("5cda5bc5b50a6c6dd317adcb"), "ClientName" : "John", "ClientAge" : 41 } { "_id" : ObjectId("5cda5bc6b50a6c6dd317adcc"), "ClientName" : "David", "ClientAge" : 35 }
以下是执行多次更新的查询。现在,使用以下查询,三个客户端的ClientName“ John”将具有更新的年龄-
> db.multiUpdateDemo.update({'ClientName': 'John'}, {$set: {'ClientAge': 34}}, {multi: true}); WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
让我们再次检查文件-
> db.multiUpdateDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cda5bc0b50a6c6dd317adc8"), "ClientName" : "John", "ClientAge" : 34 } { "_id" : ObjectId("5cda5bc1b50a6c6dd317adc9"), "ClientName" : "Carol", "ClientAge" : 31 } { "_id" : ObjectId("5cda5bc3b50a6c6dd317adca"), "ClientName" : "John", "ClientAge" : 34 } { "_id" : ObjectId("5cda5bc5b50a6c6dd317adcb"), "ClientName" : "John", "ClientAge" : 34 } { "_id" : ObjectId("5cda5bc6b50a6c6dd317adcc"), "ClientName" : "David", "ClientAge" : 35 }