Creating Databases in MongoDB

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. In MongoDB, databases are created dynamically when data is inserted into them. However, you can explicitly create databases as well. In this topic, we'll explore the process of creating databases in MongoDB.

Basic Database Creation

To create a new database in MongoDB, you can use the use command followed by the name of the database you want to create.

				
					use mydatabase
				
			

Explanation:

  • The use command is used to create a new database or switch to an existing one.
  • In this example, mydatabase is the name of the new database to be created. If the database does not already exist, MongoDB will create it.

Verifying the Current Database

To check which database you’re currently using, you can use the db command without any arguments.

				
					db
				
			

Explanation:

  • The db command is used to display the current database being used.
  • When used without any arguments, it returns the name of the current database.

Switching Databases

If you want to switch to a different database, you can use the use command again with the name of the database you want to switch to.

				
					use anotherdatabase
				
			

Explanation:

  • Similar to creating a new database, the use command can also be used to switch between existing databases.
  • In this example, anotherdatabase is the name of the database we want to switch to.

Listing Databases

To list all databases available on your MongoDB server, you can use the show dbs command.

				
					show dbs
				
			

Explanation:

  • The show dbs command is used to display a list of all databases present on the MongoDB server.
  • It lists both the existing databases and ones that are currently empty.

Dropping a Database

If you want to delete a database, you can use the db.dropDatabase() command.

				
					use unwanted_database
db.dropDatabase()
				
			

Explanation:

  • The db.dropDatabase() command is used to delete the currently selected database.
  • In this example, unwanted_database is the name of the database we want to delete.

Creating databases in MongoDB is a straightforward process. While MongoDB automatically creates databases when data is inserted into them, you can also explicitly create them using the use command. You can switch between databases, list all available databases, and delete unwanted databases using simple commands. MongoDB's flexibility and ease of use make it a popular choice for many developers. Happy Coding!❤️

Table of Contents