Skip to main content

Databases

In this tutorial, we're going to cover the concept of databases in MongoDB. As a beginner, it's crucial to understand this aspect as it forms the foundation upon which we can build our knowledge and skills.

What is a Database?

A database is an organized collection of data stored and accessed electronically. In MongoDB, a database is not just a place where data is stored, but it's where we store collections of documents.

In simpler terms, you can think of a database like a box in a warehouse, where the warehouse is MongoDB. This box (database) can contain smaller boxes (collections), and these collections contain individual items (documents).

Creating a Database

In MongoDB, you don't need to explicitly create a database. It gets created when you save the very first document into it.

To create a database in MongoDB, we use the use DATABASE_NAME command. If the specified database does not exist, MongoDB creates a new database.

Here is a syntax example:

use my_database

This command will create a new database named my_database if it doesn't exist. If it does exist, then it will return that database.

Checking Your Current Database

If you want to check your currently selected database, use the db command.

Here is an example:

db

This command will return the name of the database you're currently using.

Listing All Databases

You can list all databases in your MongoDB server using the show dbs command.

Here is an example:

show dbs

This command will output all existing databases in your MongoDB server.

Dropping a Database

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

Here is a syntax example:

use my_database
db.dropDatabase()

This command will delete the currently selected database.

Conclusion

Understanding databases in MongoDB is a crucial step for any beginner. Remember, a database is where we store collections of documents. We can create a new database using the use DATABASE_NAME command, check our currently selected database using the db command, list all databases using the show dbs command, and delete a database using the db.dropDatabase() command.

In the next sections, we will cover more MongoDB concepts, such as collections and documents, which will further build on your understanding of how MongoDB works.