How to create a db in MongoDB?

How to Create a Database in MongoDB

Creating a database in MongoDB is straightforward and does not require explicit commands like traditional relational databases. Here’s how you can create a database:

1. Switch to the Database

  • MongoDB does not create a database until you insert data into it.
  • Use the use command to switch to or create a new database.

Example:

use myDatabase

If myDatabase does not exist, MongoDB will prepare to create it once you add data.

2. Insert Data into the Database

  • MongoDB creates the database only when a collection is created, and documents are added.

Example:

db.myCollection.insertOne({ name: "Alice", age: 25 });

This command:

  • Creates the collection myCollection in myDatabase.
  • Adds a document to myCollection.
  • Automatically creates myDatabase.

3. Verify the Database Creation

  • List all databases to confirm creation using the show dbs command.
  • Note: A newly created database will not appear in the list until it contains data.

Example:

show dbs

4. Optional: Create a Collection Explicitly

You can also create a collection explicitly before inserting data.

db.createCollection("myCollection");

Notes

  • MongoDB databases are lightweight and only occupy space once data is added.
  • MongoDB does not require schema definitions, making it highly flexible for development.

For more in-depth knowledge:

This approach makes database creation in MongoDB simple and intuitive for modern development needs.

TAGS
Coding Interview
System Design Interview
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
How many rounds are there in PayPal?
Is Python hard to learn?
What does Apple ask in interviews?
What is the role of middleware in a distributed system?
How do you solve a coding interview?
Is backtracking important for an interview?
Related Courses
Course image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
Discounted price for Your Region

$197

Course image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
Discounted price for Your Region

$78

Course image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
Discounted price for Your Region

$78

Image
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.