Nikolaos Plastiras
Nikolaos Plastiras

Reputation: 522

Remove a subdocument nested in an array in MongoDB

I want to remove this:

{
"val" : NumberLong(200),
"chId" : 2,
"reqSys" : "222220005031",
"old" : NumberLong(223),
"isRb" : false
},

from this:

{
"_id" : ObjectId("52d7c25480f0a83293adbbbc"),
"d" : 2014001,
"m" : 123456789,
"topups" : {
    "data" : [
            {
                    "val" : NumberLong(200),
                    "chId" : 2,
                    "reqSys" : "222220005031",
                    "old" : NumberLong(223),
                    "isRb" : false
            },
            {
                    "val" : NumberLong(150),
                    "chId" : 2,
                    "reqSys" : "222220005031",
                    "old" : NumberLong(166),
                    "isRb" : false
            }
    ],
    "total" : {
            "cnt" : 2,
            "revenue" : NumberLong(3500000)
    }
}

I would like to find the object by querying {d:2014001, m:123456789} and remove the whole object in the data array that has "val":200 if that is possible in one command. But if not, multiple commands work for me also. Have tried with $pull and $pullAll but I am missing something.

Upvotes: 31

Views: 24577

Answers (1)

Sumeet Kumar Yadav
Sumeet Kumar Yadav

Reputation: 13015

To remove sub document use $pull

This query will remove from nested sub document

 db.collection.update({ d : 2014001 , m :123456789},
                      {$pull : { "topups.data" : {"val":NumberLong(200)} } } )

Upvotes: 52

Related Questions