Design Gurus Logo

How to create a db in MongoDB?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

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:

  • Relational Database Design and Modeling for Software Engineers: Learn database creation and design principles. Check it out
  • Grokking SQL for Tech Interviews: Transition from SQL to MongoDB concepts smoothly. Explore here

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

TAGS
Coding Interview
System Design Interview
CONTRIBUTOR
TechGrind

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
Related Courses
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.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
Grokking Advanced Coding Patterns for Interviews
Master advanced coding patterns for interviews: Unlock the key to acing MAANG-level coding questions.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.