Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a subdocument nested in an array in MongoDB

Tags:

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.

like image 985
Nikolaos Plastiras Avatar asked Feb 27 '14 10:02

Nikolaos Plastiras


People also ask

How do I remove a nested object in MongoDB?

To remove an element from a doubly-nested array in MongoDB document, you can use $pull operator. Now field "UserZipCode": "20010" has been removed from a doubly-nested array.

How do I remove a specific element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.


1 Answers

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)} } } ) 
like image 90
Sumeet Kumar Yadav Avatar answered Sep 21 '22 21:09

Sumeet Kumar Yadav