Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb remove subdocument from document

Tags:

mongodb

I have a collection with a following data:

{

  "_id" : ObjectId("4e3951905e746b3805000000"),
  "m" : "hello",
  "r" : [{
      "_id" : ObjectId("4e3951965e746b8007000000"),
      "u" : 3,
      "m" : "response1"
    }, {
      "_id" : ObjectId("4e39519d5e746bc00f000000"),
      "u" : 3,
      "m" : "response2"
    }, {
      "_id" : ObjectId("4e3953dc5e746b5c07000000"),
      "u" : 3,
      "m" : "response3"
    }, {
      "_id" : ObjectId("4e3953ea5e746bd40f000001"),
      "u" : 3,
      "m" : "response"
    }],
  "u" : 3,
  "w" : 3
}
{
  "_id" : ObjectId("4e3952c75e746bd807000001"),
  "m" : "asdfa",
  "r" : [{
      "_id" : ObjectId("4e39544e5e746bc00f000001"),
      "u" : 3,
      "m" : "response5"
    }],
  "u" : 3,
  "w" : 3
}

Can anyone suggest how to remove a subdocument from a 'r' key having only id of subdocument, I am going to del?

for instance i want to del a subdocument with id 4e39519d5e746bc00f000000 So this subdocument should be deleted

{
  "_id" : ObjectId("4e39519d5e746bc00f000000"),
  "u" : 3,
  "m" : "response2"
},
like image 847
Abnormal Avatar asked Aug 03 '11 14:08

Abnormal


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 an 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.


2 Answers

It's easy, you just need to use $pull operator:

db.items.update( {}, 
{ $pull : { r : {"_id": ObjectId("4e39519d5e746bc00f000000")} } }, false, false )
like image 55
Andrew Orsich Avatar answered Oct 12 '22 08:10

Andrew Orsich


dbh.users.update({"_id": ObjectId("4e39519d5e746bc00f000000")}, {"$unset":{"r":1}},False,False)

Try using unset

Reference: MongoDB : Update Modifier semantics of "$unset"

like image 45
objmagic Avatar answered Oct 12 '22 08:10

objmagic