Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a single object from an array of objects in MongoDB

Tags:

mongodb

Say we have the following collection of documents:

{ "_id" : ObjectId("50a69fa904c8310609600be3"), "id" : 100, "city" : "San Francisco", "friends" : [     {   "id" : 1,   "name" : "John" },  {   "id" : 2,   "name" : "Betty" },     {   "id" : 3,   "name" : "Harry" } ] }
{ "_id" : ObjectId("50a69fc104c8310609600be4"), "id" : 200, "city" : "Palo Alto", "friends" : [     {   "id" : 1,   "name" : "Carol" },     {   "id" : 2,   "name" : "Frank" },     {   "id" : 3,   "name" : "Norman" } ] }
{ "_id" : ObjectId("50a69fc304c8310609600be5"), "id" : 300, "city" : "Los Angeles", "friends" : [   {   "id" : 1,   "name" : "Fred" },  {   "id" : 2,   "name" : "Neal" },  {   "id" : 3,   "name" : "David" } ] }
    .
    .
    .  

Now let's say that Frank (Palo Alto, id=2) is no longer my friend, and I want to delete him from the collection. I thought the following might work, but it doesn't:

db.test.update({"city":"Palo Alto"},{"$pull":{"friends.name":"Frank"}})

I'd like to be able to do something like that. Delete an object within an array within a collection of documents. How do you do this?

like image 988
Evan Zamir Avatar asked Nov 16 '12 20:11

Evan Zamir


1 Answers

You were close. The query should be like this:

db.test.update({"city":"Palo Alto"},{"$pull":{"friends":{"name":"Frank"}}});

$pull takes an object whose field specifies the field array "friends". The value {"name":"Frank"} represents the query (to run inside the array) to find the element to pull out.

like image 93
Tim Gautier Avatar answered Sep 24 '22 19:09

Tim Gautier