MongoDB - Java

MongoDB - PHP

MongoDB - Advanced

MongoDB - Useful Resources

MongoDB - Create Database



In this chapter, we will see how to create a database in MongoDB.

The use Command

MongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn't exist, otherwise it will return the existing database.

Syntax

Basic syntax of use DATABASE statement is as follows −

use DATABASE_NAME

Example - Creating a Database

If you want to use a database with name <mydb>, then use DATABASE statement would be as follows −

test> use mydb
switched to db mydb

By default, we were connected to test database.

To check your currently selected database, use the command db

mydb>db
mydb

If you want to check your databases list, use the command show dbs.

mydb>show dbs
admin    40.00 KiB
config  100.00 KiB
local    40.00 KiB

Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it.

mydb>db.movie.insertOne({"name":"tutorials point"})
{
  acknowledged: true,
  insertedIds: { '0': ObjectId('6964a3df25c4ea6b911e2621') }
}
mydb>show dbs
admin    40.00 KiB
config  100.00 KiB
local    40.00 KiB
mydb     40.00 KiB

In MongoDB default database is test. If you didn't create any database, then collections will be stored in test database.

Advertisements