6

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?

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I would have banged my head for hours trying to figure that out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.