Removing the array element in mongoDB based on the position of element

前端 未结 3 1656
予麋鹿
予麋鹿 2020-12-03 19:47

Actually I need to remove an element from the array based on its position. Using $pop we can remove element from top or bottom (considering it as a stack. 0th element at top

3条回答
  •  -上瘾入骨i
    2020-12-03 20:00

    Here's your answer MongoDB pull array element from a collection

    To remove specific element from an array of some document first you need to identify this element. For instance I have a document with array and every element of this array is an object:

    `{
        "_id" : ObjectId("5140f34888dd50971900002d"),
        "_permissions" : {
            "edit" : [
                {
                    "profile_id" : NumberLong(123),
                    "comment" : "app/project owner"
                },
                {
                    "profile_id" : NumberLong("153579099841888257"),
                    "comment" : "project admin"
                },
                {
                    "profile_id" : NumberLong("153579095869882369"),
                    "comment" : "project admin"
                }
            ],
            "view" : [
                {
                    "profile_id" : NumberLong(123),
                    "comment" : "app/project owner"
                },
                {
                    "profile_id" : NumberLong("153579099841888257"),
                    "comment" : "project admin"
                },
                {
                    "profile_id" : NumberLong("153579095869882369"),
                    "comment" : "project admin"
                }
            ]
        }
    }`
    

    So let's remove "profile_id" with "153579099841888257" value from "_permissions.view" array. Here we go

    `db.collection.update({_id: ObjectId("5140f34888dd50971900002d")}, {$pull:{"_permissions.view": {"profile_id": NumberLong("153579099841888257")}}});`
    
    1. I define scope of the object (to make sure id doesn't affect any other first found document)
    2. Identify needed element to pull out: "profile_id" with "153579099841888257" value in the "_permissions.view" array

提交回复
热议问题