Managing users and databases within MongoDB is critical to maintaining an organized and secure database environment. While adding users and creating databases are fundamental operations, there are times when you need to delete a user or an entire database.

In this tutorial, we will walk through the steps to delete a user and a database in MongoDB.

Deleting a User in MongoDB

First, you need to connect to the MongoDB shell. Open your terminal or command prompt and type the following command:

mongo

To manage users, you must switch to the admin database. The admin database is the default database for administrative tasks in MongoDB. Use the following command:

use admin

If your MongoDB instance is running with authentication, you must authenticate as a user with administrative privileges. Run the following command, replacing and with your admin user’s credentials:

db.auth('admin-user', 'password')

To delete a user, you can use the db.dropUser() method. Let’s say you want to delete a user named testUser. Use the following command:

db.dropUser('testUser')

If the user is successfully deleted, you will see:

{ "ok" : 1 }

Deleting a Database in MongoDB

If you have not already connected to MongoDB, open your terminal or command prompt and type:

mongo

Before deleting a database, it’s a good idea to list all the databases to ensure you are deleting the correct one. Use the following command:

show dbs

This command will list all databases:

admin       0.000GB
config      0.000GB
local       0.000GB
tutorialDB  0.000GB

Let’s say you want to delete a database named tutorialDB. Switch to the tutorialDB database using the following command:

use tutorialDB

To delete the tutorialDB database, use the db.dropDatabase() method:

db.dropDatabase()

If the database is successfully deleted, you will see:

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

Conclusion

In this article, we covered how to delete a user and a database in MongoDB. We started by explaining how to connect to the MongoDB shell and switch to the admin database. Then, we demonstrated how to delete a user using the db.dropUser() method. Finally, we walked through the process of deleting a database with the db.dropDatabase() method. You can follow this guide to delete a MongoDB database and user on VPS hosting from Atlantic.Net!