Deleting MongoDB documents - Part 10
We’ve seen how to create and insert new documents, and you’ve seen how to update them, well let’s take a look at how to remove them. Now remember with update, it would only affect the first one, remove isn’t like that, if you pick a field that’s not unique, it will delete all the matching records. So let’s make sure it’s unique. So I’m going to go with title; brand: “Apple”.
db.products.remove({brand: “Apple”})
What if I’d like to identify a field that may have duplicates? Now right now we have only few records, you can just look at and see if there’s duplicates. What if there’s 5,000 records? There could be a duplicate I’m not even aware of. If I notice that there are 2 duplicate records, I would simply write db.products.remove({brand: “Apple”},1) so that it would remove first record. If I had 1,000 records that matched, and I said, comma 100, it would delete the first 100. It tells me again that it relieved…removed only one, so removing only one, pretty simple. Monte Cristo has been removed.