Mongodb Query to drop the database with examples

Mongodb, a Database is a group of collections stored under a name. The collection is similar to a table in SQL databases.

We can use Mongosh or GUI clients to create and update databases and collections. let’s see how to drop the database from Mongosh

How to drop database in MongoDB

show dbsor show databases commands list out all databases in a server

moviesdb> show dbs
admin      40.00 KiB
config     72.00 KiB
ecommerce   8.00 KiB
librarydb  40.00 KiB
local      72.00 KiB
moviesdb   50.10 MiB

Let’s see how to delete librarydb database using the command line.

First, change the existing database to a new database using use database command.

moviesdb> use librarydb
switched to db librarydb

Next, db.dropDatabase() removes the database and all collections in it.

librarydb>db.dropDatabase();

Output:

{ "dropped" : "librarydb", "ok" : 1 }

To remove all users from the database.

db.dropAllUsers();

To remove specific collections from a database

librarydb> db.collection.drop();
true

It drops the specific collection and all documents from it and returns True

Delete everything in a MongoDB database

This allows you to delete all records of a collection in the database.

Suppose, you want to delete everything such as documents, collections, and databases

Sequence of comments you can do

To remove data from a collection, use deleteMany or deleteOne.

db.students.deleteMany({"name":"john"})
db.students.deleteOne({"name":"john"})

To remove entire data from an collecton,use {} with remove command

librarydb> db.students.remove({})
{ acknowledged: true, deletedCount: 0 }

use drop collection, To delete all documents and collection

db.students.drop()

dropDatabase() is to delete a database

db.dropDatabase()