mongodb中$push和$pull的使用,向內嵌的數組中刪除和添加元素
假設在集中在存在如下數據:
{ "_id" : ObjectId("5cb6e53cb4276075a2262f5b"), "results" : [ { "current" : 7.45, "origin" : 0, "target" : 100, "title" : "組織kr", "type" : 2, "director" : "c673e19320f1461d859f5c8703f7c47f", "indepartmental_needs" : "組織kr", "_id" : ObjectId("5cb7e9ba439a2716f888c14d"), "arr" : [ { "_id" : 1, "kid" : 1, "parent_id" : null }, { "_id" : 2, "kr_id" : 2, "parent_id" : 1 }, { "_id" : 3, "kr_id" : 3, "parent_id" : 1 }, { "_id" : 4, "kr_id" : 3, "parent_id" : 1 }, { "_id" : 5, "kr_id" : 1, "parent_id" : 1 } ], },
很明顯,這個數據的結構是層層嵌套的,並且arr數組中存儲了一個打平的父子相互引用的樹結構,
需求1:
需要再向arr數組中添加元素:
this.model.findOneAndUpdate( { 'results._id':mongoose.Types.ObjectId(body.ancestors) }, { $push: { "results.$.arr": { parent_id : 1, kr_id : 1 } } }, { upsert:true, 'new':true } , (err,data)=>{ //return } );
$符號是mongodb中的占位符,也就是說當我們指定一個位置或匹配到一個元素之后,這個符號會自動指向平級的元素來進行操作,
push是直接向數組中進行添加,如果不想添加重復的元素,可以選擇使用push是直接向數組中進行添加,如果不想添加重復的元素,可以選擇使用push是直接向數組中進行添加,如果不想添加重復的元素,可以選擇使用addToSet
需求2:
刪除內嵌數組中的某一元素:
this.model.findOneAndUpdate( { "results._id":mongoose.Types.ObjectId(ancestors_id) }, { $pull: { "results.$.relation_kr_draft":{ _id: { $in : arr } } } } );
同樣的,我們在這里還是使用了$占位符,在我們匹配到元素之后,占位符也自動匹配
mongo 查找對象數組中某一個或幾個匹配的屬性用 $elemMatch
new_parttime_positions: { $elemMatch: { position: ai.position.position_direct_superior, start_time: { $lte: moment().toDate() }, end_time: { $gte: moment().toDate() } } }
原文鏈接:https://blog.csdn.net/qq_42427109/article/details/89426172