1. Home
  2. MongoDB
  3. MongoDB Tutorial
  4. MongoDB – Create Database

MongoDB – Create Database

MongoDB Create Database

Creating a new database with MongoDB is a straightforward process, but there are a few prerequisites that you need to consider before you can get started. In this article, I’ll walk you through the steps for creating a MongoDB database, as well as some common mistakes to avoid. By the end of this article, you’ll have the knowledge and confidence to create a new database with MongoDB quickly and easily.

Syntax:

> use DATABASE_NAME

Limitations

MongoDB database names cannot be empty and must have fewer than 64 characters.

Create Database

First, let’s create a database called “mydb”. To do this, open the MongoDB shell and type the command “use mydb”. This will create a new database with the specified name.

> use mydb

Now, let’s add a collection to the database called “users”. To do this, enter the following command:

> db.createCollection(users)

This will create a new collection in the “mydb” database.

Next, let’s add a document to the “users” collection. To do this, enter the command

> db.users.insert({ id: 1, name: 'John Doe', age: 24 })

Show Databases

– After inserting the first record the database will be listed in show dbs command.

> show dbs

local           0.000GB
mydb            0.000GB

Also, You can run the db command to find the currently selected database.

> db

mydb

Finally, make sure to back up your data regularly. If you make a mistake while creating a new database, you can always restore the data from a backup. This will prevent you from losing any important data.

Tags ,