您可以使用bulkWrite()
。让我们创建一个包含文档的集合-
> db.demo105.insertOne( { _id:'101', Name:'Chris', Details:[{ Marks1:60, Marks2:70, Marks3:70 }, { Marks1:70, Marks2:70, Marks3:90 }] } ); { "acknowledged" : true, "insertedId" : "101" }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo105.find().pretty();
这将产生以下输出-
{ "_id" : "101", "Name" : "Chris", "Details" : [ { "Marks1" : 60, "Marks2" : 70, "Marks3" : 70 }, { "Marks1" : 70, "Marks2" : 70, "Marks3" : 90 } ] }
以下是在元素不存在的情况下插入数组的查询,否则会用多种条件对其进行更新-
> db.demo105.bulkWrite([ ... { "updateOne": { ... "filter": { ... "_id": "101", ... "Details": { ... "$elemMatch": { Marks2: 70, Marks3: 70 } ... } ... }, ... "update": { ... "$set": { "Details.$.Marks3": 96 } ... } ... }}, ... { "updateOne": { ... "filter": { ... "_id": "101", ... "Details": { ... "$not": { ... "$elemMatch": { Marks2: 70, Marks3: 70 } ... } ... } ... }, ... "update": { ... "$push": { "Details": { Marks1: 94, Marks2: 97,Marks3:99} } ... } ... }}, ... { "updateOne": { ... "filter": { "_id": 101 }, ... "update": { ... "$setOnInsert": { ... "Details": [ ... { Marks1: 34, Marks2: 67,Marks3:87 } ... ] ... } ... }, ... "upsert": true ... }} ... ]) { "acknowledged" : true, "deletedCount" : 0, "insertedCount" : 0, "matchedCount" : 2, "upsertedCount" : 1, "insertedIds" : { }, "upsertedIds" : { "2" : 101 } }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo105.find().pretty();
这将产生以下输出-
{ "_id" : "101", "Name" : "Chris", "Details" : [ { "Marks1" : 60, "Marks2" : 70, "Marks3" : 96 }, { "Marks1" : 70, "Marks2" : 70, "Marks3" : 90 }, { "Marks1" : 94, "Marks2" : 97, "Marks3" : 99 } ] } { "_id" : 101, "Details" : [ { "Marks1" : 34, "Marks2" : 67, "Marks3" : 87 } ] }