在单个MongoDB查询中更新多行?
使用的概念initializeUnorderedBulkOp()
。首先让我们创建一个包含文档的集合-
>db.upDateMultipleRowsDemo.insertOne({"CustomerName":"John","CustomerPurchaseAmount":500}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb06d78f205348bc626") } >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Chris","CustomerPurchaseAmount":700}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb26d78f205348bc627") } >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"David","CustomerPurchaseAmount":50}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb36d78f205348bc628") } >db.upDateMultipleRowsDemo.insertOne({"CustomerName":"Larry","CustomerPurchaseAmount":1900}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6ceb46d78f205348bc629") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.upDateMultipleRowsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd6ceb06d78f205348bc626"), "CustomerName" : "John", "CustomerPurchaseAmount" : 500 } { "_id" : ObjectId("5cd6ceb26d78f205348bc627"), "CustomerName" : "Chris", "CustomerPurchaseAmount" : 700 } { "_id" : ObjectId("5cd6ceb36d78f205348bc628"), "CustomerName" : "David", "CustomerPurchaseAmount" : 50 } { "_id" : ObjectId("5cd6ceb46d78f205348bc629"), "CustomerName" : "Larry", "CustomerPurchaseAmount" : 1900 }
以下是在单个查询中更新多行的查询-
> var manyUpdateValue = db.upDateMultipleRowsDemo.initializeUnorderedBulkOp(); > manyUpdateValue.find({ _id: ObjectId("5cd6ceb06d78f205348bc626")}).updateOne({$set:{"CustomerName":"Bob" }}); > manyUpdateValue.find({ _id: ObjectId("5cd6ceb36d78f205348bc628")}).updateOne({$set:{"CustomerPurchaseAmount":56544444}}); > manyUpdateValue.execute(); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 0, "nUpserted" : 0, "nMatched" : 2, "nModified" : 2, "nRemoved" : 0, "upserted" : [ ] })
让我们再次检查所有文件-
> db.upDateMultipleRowsDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd6ceb06d78f205348bc626"), "CustomerName" : "Bob", "CustomerPurchaseAmount" : 500 } { "_id" : ObjectId("5cd6ceb26d78f205348bc627"), "CustomerName" : "Chris", "CustomerPurchaseAmount" : 700 } { "_id" : ObjectId("5cd6ceb36d78f205348bc628"), "CustomerName" : "David", "CustomerPurchaseAmount" : 56544444 } { "_id" : ObjectId("5cd6ceb46d78f205348bc629"), "CustomerName" : "Larry", "CustomerPurchaseAmount" : 1900 }