28

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.

Vince Bowdren
  • 8,326
  • 3
  • 31
  • 56
Nikolaos Plastiras
  • 484
  • 1
  • 7
  • 20
  • possible duplicate of [How to remove an element from a doubly-nested array in a MongoDB document](http://stackoverflow.com/questions/5228210/how-to-remove-an-element-from-a-doubly-nested-array-in-a-mongodb-document) – Dan Dascalescu Feb 27 '14 at 10:15

1 Answers1

50

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)} } } )
Community
  • 1
  • 1
Sumeet Kumar Yadav
  • 11,912
  • 6
  • 43
  • 80