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是直接向數組中進行添加,如果不想添加重複的元素,可以選擇使用addToSet

需求2:
刪除內嵌數組中的某一元素:

this.model.findOneAndUpdate(
            {
                "results._id":mongoose.Types.ObjectId(ancestors_id)
            },
            {
                $pull:
                {
                    "results.$.relation_kr_draft":{
                        _id: { 
                            $in : arr 
                            }
                }
            }
        }
        );

同樣的,我們在這裏還是使用了$佔位符,在我們匹配到元素之後,佔位符也自動匹配

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章