要执行多个写入操作,请使用bulkWrite()。让我们创建一个数组列表值。以下是查询-
> const arrayList = [ ... {"Value1":100, "Value2":200, "Name": "John"}, ... {"Value1":100, "Value2":200, "Name": "Bob"} ... ]; > let op1 = []; > arrayList.forEach(({ Value1, Value2, Name }) => { ... op1.push({ ... "updateOne": { ... "filter": { Name}, ... "update": { "$set": { Value1, Value2, Name } }, ... "upsert": true ... } ... }) ... }); > db.demo397.bulkWrite(op1); { "acknowledged" : true, "deletedCount" : 0, "insertedCount" : 0, "matchedCount" : 0, "upsertedCount" : 2, "insertedIds" : { }, "upsertedIds" : { "0" : ObjectId("5e5e8c07f995e1718151981c"), "1" : ObjectId("5e5e8c07f995e1718151981d") } }
在find()方法的帮助下显示集合中的所有文档-
> db.demo397.find();
这将产生以下输出-
{ "_id" : ObjectId("5e5e8c07f995e1718151981c"), "Name" : "John", "Value1" : 100, "Value2" : 200 } { "_id" : ObjectId("5e5e8c07f995e1718151981d"), "Name" : "Bob", "Value1" : 100, "Value2" : 200 }