Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from nested array mongodb

i have the following document , it has two array's , one inside the other ,
attachment array and files array inside attachment array . i want to delete an element inside files array using this element _id . but its not working with me , i tried this code , it return { n: 144, nModified: 0, ok: 1 }

   Invoice.update({}, {
        $pull: {
            "attachment":
            {
                "files":
                {
                    $elemMatch:
                        { _id: ObjectId("5b7937014b2a961d082de9bf") }
                }
            }
        }
    }, { multi: true })
        .then(result => {
            console.log("delete", result);


        });

this is how the document looks like document


1 Answers

You can try below update query in 3.6 version.

Invoice.update( 
 {}, 
 {"$pull":{"attachment.$[].files":{_id:ObjectId("5b7969ac8fb15f3e5c8e844e")}}}, 
 {"multi": true}, function (err, result) {console.log(result);
});

Use db.adminCommand( { setFeatureCompatibilityVersion: 3.6 or 4.0 depending on your version } ) if your are upgrading from old version.

like image 161
s7vr Avatar answered Nov 19 '25 09:11

s7vr