How to Create a Database in MongoDB: Simple Steps
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.
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.
use shopDB // Switch to shopDB // Insert a product document db.products.insertOne({item: "book", price: 15})
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"})
use testDB // No insert here, database not created // Correct way use testDB db.users.insertOne({name: "Alice"})
Quick Reference
| Command | Description |
|---|---|
| use | Switch to or create a database on first write |
| db.collection.insertOne(document) | Insert a document to create the database and collection |
| show dbs | List all databases with data |
| show collections | List collections in the current database |