0
0
MongodbHow-ToBeginner · 3 min read

How to Create a Database in MongoDB: Simple Steps

In MongoDB, you create a database by switching to it using the use command in the shell. The database is created only when you insert data into it, so after switching, insert a document to finalize creation.
📐

Syntax

To create or switch to a database in MongoDB shell, use the use <databaseName> command. This does not create the database immediately but sets the context. The database is created when you insert data into a collection.

  • use <databaseName>: Switches to the specified database or creates it upon first write.
  • db.collection.insertOne(): Inserts a document into a collection, triggering database creation.
mongodb
use myNewDatabase
// Switch to 'myNewDatabase', creates it on first insert

// Insert a document to create the database
db.myCollection.insertOne({name: "example"})
💻

Example

This example shows how to create a database named shopDB by switching to it and inserting a document into a collection called products. The database is created only after the insert.

mongodb
use shopDB
// Switch to shopDB

// Insert a product document
db.products.insertOne({item: "book", price: 15})
Output
{ "acknowledged" : true, "insertedId" : ObjectId("someObjectId") }
⚠️

Common Pitfalls

Many beginners expect the use command alone to create a database immediately, but MongoDB creates the database only after data is inserted. Also, inserting into a collection without switching to the correct database will create data in the wrong place.

Wrong way:
use testDB (no insert, no database created)

Right way:
use testDB
db.users.insertOne({name: "Alice"})

mongodb
use testDB
// No insert here, database not created

// Correct way
use testDB
db.users.insertOne({name: "Alice"})
Output
{ "acknowledged" : true, "insertedId" : ObjectId("someObjectId") }
📊

Quick Reference

CommandDescription
use Switch to or create a database on first write
db.collection.insertOne(document)Insert a document to create the database and collection
show dbsList all databases with data
show collectionsList collections in the current database

Key Takeaways

Use the 'use ' command to switch to or prepare a database.
A MongoDB database is created only after you insert data into it.
Always insert a document to finalize database creation.
Check existing databases with 'show dbs' after inserting data.
Be sure to switch to the correct database before inserting data.