Database
NoSQL
MongoDB
CRUD Operations
Create Database

MongoDB - Create Database

Introduction

MongoDB is a popular NoSQL database known for its flexibility, scalability, and simplicity. Unlike traditional SQL databases, creating a database in MongoDB is dynamic and does not require predefined schemas. Instead, databases in MongoDB are created implicitly when data is added, making the process more seamless for developers.

The use Command

In MongoDB, databases are not created explicitly. Instead, you use the use command to switch to a database. If the specified database does not exist, MongoDB will automatically create it once data is inserted. This command allows you to set the current working context to the desired database.

How It Works

  • The use command is used to switch the context to the desired database.
  • If the database already exists, it will switch to it; if not, it will create it when data is inserted.
use DATABASE_NAME

Checking the Current Database

To verify which database you are working on, you can use a command to display the current database name. This helps confirm that you are operating within the intended database context.

> db

Viewing All Databases

To see all databases present in MongoDB, you can use a command that lists them. It’s important to note that only databases containing data will appear in this list. If your database does not yet have any documents, it will not be shown.

> show dbs

Inserting Data to Create the Database

In MongoDB, a database is created only when it contains data. Therefore, after switching to a new database, inserting at least one document is necessary for it to be fully recognized. This approach ensures that only databases with actual content are maintained.

> db.collection.insert({"name": "example"})

Default Database

MongoDB has a default database called test. If you don’t specify any particular database, MongoDB uses this test database for storing data. It’s suitable for development and testing but is not recommended for production use.

Key Points to Remember

  1. Implicit Creation: Databases in MongoDB are not created immediately when using the use command; they are created only after inserting data.

  2. Switching Context: The use command sets the working environment to a specific database.

  3. Database Visibility: Only databases containing data are listed when you check all databases. Empty databases are not shown.

  4. Default Environment: MongoDB defaults to a test database, which is useful for experimentation but should be avoided for critical applications.

Conclusion

Creating a database in MongoDB is a straightforward process that revolves around data insertion. Using the use command, you can set the database context, and the actual creation of the database occurs when data is added. This method of managing databases is efficient, ensuring that only active, data-containing databases exist within your MongoDB environment.