阵列插入元素不存在时插入,存在时更新(多个条件)?
你可以使用 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 } ] }
广告