DEV Community

Cover image for Learn MongoDB: Delete Documents
Paras 🧙‍♂️
Paras 🧙‍♂️

Posted on • Updated on

Learn MongoDB: Delete Documents

Deleting documents is one last task that we need to study to finish the CRUD functionality. Deleting documents is similar to finding data. The only difference is, instead of getting the result, we want to delete that data. So, all the knowledge you gained from the post "querying document" , will be applied here.


Table Of Content:


Delete Methods in MongoDB

Main methods that we use in deleting docs are:

  • deleteOne
  • deleteMany

Methods that are mostly for database administrators and not used at application level are:

  • collection.drop()
  • db.dropDatabase()

We will use our previous, trainers collection, to understand these methods.
Following is the structure of document in trainers collection:

{
   name: "Ash",
   age: 18,
   pokemons: [
      { name: "pikachu", type: "electric", level: 16 },
      { name: "charizard", type: "fire", level: 30 },
      { name: "squirtle", type: "water", level: 12 }
   ],
   badges: ["boulder badge", "cascade badge"],
   exp: 200,
   currentTown: "Pallet Town"
}
Enter fullscreen mode Exit fullscreen mode

Examples

  • deleteOne() : this method deletes the first document that matches our query. So, even if the query finds 20 documents, it will only delete the first one.
# delete trainer Ash
> db.trainers.deleteOne({ name: "Ash" })
Enter fullscreen mode Exit fullscreen mode
  • deleteMany() : this method deletes all the documents that matches our query.
# delete trainers with age greater than 20
> db.trainers.deleteMany({
    age: { $gt: 20 }
})

# delete all trainers from the collection
> db.trainers.deleteMany({})
Enter fullscreen mode Exit fullscreen mode

I won't go deep into selecting nesting fields because it is already covered in the query documents post. There, all the operators and types of queries are explained with example.

  • collection.drop() : drop method, when used on a collection, deletes the whole collection from our database. This method is not used at application level because we don't usually delete whole collection.
# drop trainers collection
> db.trainers.drop()
Enter fullscreen mode Exit fullscreen mode
  • db.dropDatabase() : with this method, you can delete the whole database (sounds fun, isn't it?). Again, we don't use this method in our application for the same reason.
# switch to a db and use the following
> db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

So, we managed to get rid of all the database and collections we had.


That was it, we learned to delete docs, collections and databases.

In the next post, we will learn about indexes. They are pretty fun. They increase the speed of our queries even in a large collection of data.

Hope you are having fun learning mongoDB.

Next Post : Working with Indexes

Prev Post : Update documents

Top comments (0)