0

I have a mongodb collection containing an array of objects, and I'd like to remove one or more of the array objects based on their properties.

Example document from my collection:

nickname: "Bob",
isLibrarian: false,
region: "South America",
favoriteBooks: [
    {
        title: "Treasure Island",
        author: "Robert Louis Stevenson"
    },
    {
        title: "The Great Gatsby",
        author: "F. Scott Fitzgerald"
    },
    {
        title: "Kidnapped",
        author: "Robert Louis Stevenson"
    }
]

In this example, how do I remove, from each of the documents in my collection, all objects within the favoriteBook array whose author matches "Robert Louis Stevenson"?

So that afterwards this user document would be

nickname: "Bob",
isLibrarian: false,
region: "South America",
favoriteBooks: [
    {
        title: "The Great Gatsby",
        author: "F. Scott Fitzgerald"
    }
]

and other documents in the collection would be equally trimmed of books by Stevenson.

Thank you in advance for any insight! I love MongoDB but I'm wondering if I've bitten off more than I can chew here...

1 Answer 1

2

The below line of mongodb will help you to delete the books that matches a particular author

db.collection.update(
   {},
   {$pull:{favoriteBooks:{author:"Robert Louis Stevenson"}}},
   {multi:true}
);
Sign up to request clarification or add additional context in comments.

3 Comments

added multi:true since OP specified this should be done to all documents in the collection, also formatted the code.
Doesn't seem to work. The book objects remain within the favoriteBooks array.
Oops, it does work after all! At least in this contrived example. Now to figure out why it doesn't work with my more complex collection (constructed using the same structure). Thanks!

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.