mongo-db
  1. mongo-db-create-database

Create Database - ( Database and Collection Operations )

In MongoDB, a database is a container for collections, which in turn are containers for documents. In this tutorial, we will discuss how to create a database in MongoDB.

Syntax

To create a new database in MongoDB, you can use the following command in the Mongo shell:

use YOUR_DATABASE_NAME

If the database doesn't exist, MongoDB will create it for you. If the database does exist, MongoDB will switch to that database.

Example

Let us create a new database called "mydb" using the Mongo shell:

use mydb

This will create a new database called "mydb" if it doesn't exist, otherwise it will switch to the "mydb" database.

Output

You should see the output switched to db mydb in the Mongo shell.

Explanation

When you use the use command in the Mongo shell, MongoDB will look for the database you specified. If the database doesn't exist, MongoDB will create it for you. If the database already exists, MongoDB will switch to that database.

Use

Creating a database is the first step in working with MongoDB. You can then create collections inside the database and insert documents into the collections.

Important Points

  • To create a new database in MongoDB, use the use command in the Mongo shell.
  • If the database doesn't exist, MongoDB will create it for you. If the database already exists, MongoDB will switch to that database.

Summary

In this tutorial, we discussed how to create a database in MongoDB. We covered the syntax, example, output, explanation, use, and important points of creating a database in MongoDB. By creating a database, you can then create collections and add documents to the collections in MongoDB.

Published on: