How to Delete Documents in MongoDB
So far we've gone through a number of ways to query documents in Mongo. We've also talked about inserting either single or multiple documents.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide, we're going to talk about how we can remove documents. So here I'm going to start off with a query I'm going to say db and then books because that's the name of our collection. And then we're going to pass in remove and that is the function we're going to pass. It expects an object so I can say name and then here I'll say OOP programming. Because if you remember we have a number of those guides there and those are they have different names and titles and so I just want to remove all of them to be able to clean them up. So right here I can I have a couple of different options. First is where I can run this and it's going to remove all of the items. Now if I passed in a second element so if I passed in say a 1 it's only going to remove one of the items. So here if I run this you can see that it gives us a return result and says number removed is 1.

large

If I go back and say db.books.find and pass in name OOP programming this is going to tell us that we still have a number of books left there.

db.books.find({name: "OOP Programming"})

Now if we run it again and remove that 1 flag now it has removed 2 of them and if we run the query again you can see that we have no documents with the name of OOP programming.

So those are the two common ways where you can remove documents in Mongo. The first is where you can pass in an explicit number on how many you want to remove and the other is where you simply want to delete all of the documents that match that query.

Code

db.books.remove({name: "OOP Programming"}, 1) // Removes a single document
db.books.remove({name: "OOP Programming"}) // Removes all documents