添加多项文档的 MongoDB 查询
若要执行多项写操作,请使用 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 }
广告