Neko Jiru
Neko Jiru

Reputation: 45

Using mongodb, how can I remove an object from an array based on one of its properties?

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

Upvotes: 0

Views: 132

Answers (1)

kishore
kishore

Reputation: 1748

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}
);

Upvotes: 2

Related Questions