如何在 MongoDB 中更新多份文档?
您需要使用 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 }
以下是执行多更新的查询。现在,3 个客户端的 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 }
广告