要通过单个查询更新许多文档,请在MongoDB中使用 bulkWrite()。让我们创建一个包含文档的集合-
> db.demo760.insertOne({id:1,details:{Value1:100,Value2:50}}); { "acknowledged" : true, "insertedId" : ObjectId("5eb0309f5637cd592b2a4aee") } > db.demo760.insertOne({id:2,details:{Value1:60,Value2:70}}); { "acknowledged" : true, "insertedId" : ObjectId("5eb030a15637cd592b2a4aef") } > db.demo760.insertOne({id:3,details:{Value1:80,Value2:90}}); { "acknowledged" : true, "insertedId" : ObjectId("5eb030a15637cd592b2a4af0") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo760.find();
这将产生以下输出-
{ "_id" : ObjectId("5eb0309f5637cd592b2a4aee"), "id" : 1, "details" : { "Value1" : 100, "Value2" : 50 } } { "_id" : ObjectId("5eb030a15637cd592b2a4aef"), "id" : 2, "details" : { "Value1" : 60, "Value2" : 70 } } { "_id" : ObjectId("5eb030a15637cd592b2a4af0"), "id" : 3, "details" : { "Value1" : 80, "Value2" : 90 } }
以下是使用MongoDB中的一个查询来更新许多文档的查询-
> db.demo760.bulkWrite([ ... { ... updateOne: { ... filter: {id: 1}, ... update: {$set: {'details.Value1': 900, 'details.Value2': 500}}, ... } ... }, ... { ... updateOne: { ... filter: {id: 2}, ... update: {$set: {'details.Value1': 1000, 'details.Value2': 2000}}, ... }, ... } ... ]) { "acknowledged" : true, "deletedCount" : 0, "insertedCount" : 0, "matchedCount" : 2, "upsertedCount" : 0, "insertedIds" : { }, "upsertedIds" : { } }
在find()方法的帮助下显示集合中的所有文档-
> db.demo760.find();
这将产生以下输出-
{ "_id" : ObjectId("5eb0309f5637cd592b2a4aee"), "id" : 1, "details" : { "Value1" : 900, "Value2" : 500 } } { "_id" : ObjectId("5eb030a15637cd592b2a4aef"), "id" : 2, "details" : { "Value1" : 1000, "Value2" : 2000 } } { "_id" : ObjectId("5eb030a15637cd592b2a4af0"), "id" : 3, "details" : { "Value1" : 80, "Value2" : 90 } }