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"
},
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.
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.
It's easy, you just need to use $pull operator:
db.items.update( {},
{ $pull : { r : {"_id": ObjectId("4e39519d5e746bc00f000000")} } }, false, false )
dbh.users.update({"_id": ObjectId("4e39519d5e746bc00f000000")}, {"$unset":{"r":1}},False,False)
Try using unset
Reference: MongoDB : Update Modifier semantics of "$unset"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With