Create Your First MongoDB Database
Learn to create your first MongoDB database step by step. This tutorial covers the core concepts, hands-on exercises, troubleshooting tips, and what to explore next in the MongoDB track.
Focus: create your first mongodb database
You've heard all the hype about MongoDB—flexible documents, blazing-fast queries, horizontal scaling—but when you finally open the shell, you're staring at a blank prompt. Where do you start? How do you actually create your first MongoDB database? In this lesson, you'll move from theory to practice: you'll stand up a database, add your first collection, insert documents, and query them back—all while avoiding the classic pitfalls that trip up beginners. By the end, you'll have a working MongoDB database and the confidence to build on it in the next lessons.
The problem this lesson solves
When you're new to MongoDB, the biggest roadblock isn't the syntax—it's the mental model. Traditional SQL databases require you to predefine schemas, create tables, and set up relationships before you can store a single row. MongoDB flips that entirely: you can create a database and start inserting data with zero upfront schema design. That freedom is powerful, but it also means you might not know where to begin. "Do I need to create the database first? How do collections get made? What's a document?"
This lesson solves that confusion by walking you through the exact steps to create your first MongoDB database—from connecting to the server to verifying your data. You'll learn the essential commands, see real output, and understand the underlying mechanics. No more guessing: after this, you'll be able to create a database, add data, and query it like a pro.
Core concept / mental model
Think of MongoDB as a filing cabinet with sticky notes. Each drawer is a database, each folder is a collection, and each sticky note is a document. Unlike a rigid Excel spreadsheet, each sticky note can hold different fields—one might have a name and email, another might add a phone number. That's the beauty of the flexible document model.
Here are the key terms you'll use constantly:
- Database – The top-level container. Holds one or more collections. In MongoDB, a database isn't materialized until you put data in it—creating it is more like "declaring" it.
- Collection – A group of documents, analogous to a table in SQL. Collections don't enforce a schema; documents can have varying fields.
- Document – A single record, stored as BSON (binary JSON). Think of it as a JSON object with
key: valuepairs. - BSON – A binary-encoded version of JSON that supports additional data types like
ObjectIdandDate.
The critical insight: MongoDB creates databases and collections lazily. When you run use mydb, you're not actually creating anything yet—you're just switching context. The database only appears once you insert your first document. Understanding this saves you from wondering why your database didn't show up in show dbs.
How it works step by step
Let's walk through the logical sequence of creating and using a database. We'll use mongosh, the modern MongoDB shell, but the commands apply to drivers too.
Step 1: Start the MongoDB server
Before anything, ensure mongod (the server) and mongosh (the shell) are installed and running. If you installed via Homebrew on macOS, you can start it with:
brew services start mongodb-community
On Ubuntu, use sudo systemctl start mongod. Verify with mongosh --version.
Step 2: Connect to the shell
Run mongosh in your terminal. You'll see a prompt like test> — this means you're connected to the local server and currently using a default database named test.
Step 3: Switch to or create your database
Use the use command to switch to a database. If it doesn't exist, MongoDB will create it when you add data.
use myNewDatabase
Step 4: Insert your first document
Use insertOne to add a document to a collection. This simultaneously creates the collection and the database if they didn't exist.
db.users.insertOne({ name: "Alex", age: 30, email: "alex@example.com" })
Step 5: Verify and query
Run show dbs to see your database in the list, and db.users.find() to retrieve your document.
That's the entire flow. Now let's put it into practice with a hands-on walkthrough.
Hands-on walkthrough
Let's build a small blog database. We'll create a database called blog, add a users collection, insert a few documents, and query them.
1. Connect and switch database
mongosh
use blog
Output: switched to db blog
2. Insert users with different structures
db.users.insertOne({ name: "Alice", email: "alice@example.com", age: 28 })
db.users.insertOne({ name: "Bob", email: "bob@example.com", age: 34, role: "admin" })
Notice Bob has an extra role field—MongoDB allows this. Each insert returns an acknowledged: true and an insertedId.
3. Add a posts collection and insert documents
db.posts.insertMany([
{ title: "First Post", author: "Alice", tags: ["intro", "mongodb"] },
{ title: "Second Post", author: "Bob", tags: ["database"] }
])
insertMany takes an array of documents—much faster than separate insertOne calls.
4. Query your data
db.users.find()
db.posts.find({ author: "Alice" })
The first returns all users, the second filters posts by author.
5. Check your databases and collections
show dbs
show collections
Expected output for show dbs includes blog (with a size like 40.00 KiB). show collections shows users and posts.
Full script example
Here's a complete shell session for a quick start:
# Run this in your terminal
mongosh --quiet
use inventory
db.items.insertOne({ sku: "A123", name: "Widget", qty: 100 })
db.items.find()
show dbs
After running, you'll see your document printed in the shell, and inventory listed in show dbs.
Compare options / when to choose what
When creating a database, you have a few choices at the server level: local instance, MongoDB Atlas, or a Docker container. Here's a quick comparison:
| Approach | Pros | Cons | Best for |
|---|---|---|---|
| Local install | Full control, no internet | Requires setup on your machine | Learning, local dev |
| MongoDB Atlas (cloud) | Free tier, managed, accessible anywhere | Requires internet, learning curve | Production, team collaboration |
| Docker container | Isolated env, easy cleanup | Slight overhead, still need local Docker | Reproducible dev environments |
Pro tip: For this lesson, a local install or Docker is fine. Atlas is great later when you want to share your database with teammates.
Also, within the shell, choose between insertOne (single document, human-readable) and insertMany (batch insert, efficient for many records). Use insertOne when you need individual confirmation; use insertMany for bulk loading.
Troubleshooting & edge cases
Here are common issues you'll encounter and how to fix them.
1. Database not showing up in show dbs
You ran use mydb but show dbs doesn't list it. Why? MongoDB only creates the database when you insert the first document. Fix: insert a document.
use mydb
db.anything.insertOne({ test: true })
show dbs
2. mongosh: command not found
MongoDB shell isn't installed or not in your PATH. Ensure you installed mongosh (separate from the server). Check with which mongosh. On Ubuntu, install with sudo apt install mongodb-mongosh.
3. Duplicate _id error
If you try to insert a document with an _id that already exists, you'll get a duplicate key error. Fix: let MongoDB auto-generate _id (type ObjectId) or ensure uniqueness yourself.
4. Incorrect database name (case sensitivity)
Database names are case-sensitive on Unix systems. use MyDB and use mydb are different. Stick to a consistent naming convention.
What you learned & what's next
You've just created your first MongoDB database, added collections and documents, and queried them back. You now understand the lazy creation behavior, the document model, and how insertOne/insertMany work. You're ready to dive deeper: next in the track, you'll learn about CRUD operations — reading, updating, and deleting documents with filters. You'll also explore how to design schemas for real-world applications.
Remember: The database doesn't exist until you put data in it. That's the fundamental shift from SQL.
Continue to the next lesson to master querying and updating your data.
Practice recap
Now you try: open mongosh, create a database called library, add a books collection with three documents (vary the fields, e.g., some have author, some have genres), and query all books. Then check show dbs to confirm the database appeared. This will cement the lazy creation and flexible schema concepts.
Common mistakes
- Running
use mydband expecting the database to appear inshow dbsimmediately — MongoDB creates databases lazily, only when the first document is inserted. - Forgetting to install or start the MongoDB server (
mongod) and then getting connection errors inmongosh. - Trying to insert a document with your own
_idthat duplicates an existing one, causing aDuplicateKeyerror. - Assuming collections must be created explicitly — they auto-create on first insert, which trips up SQL refugees.
Variations
- Use
insertOne()vsinsertMany()— choose based on whether you're inserting a single record or batch importing many documents. - Create the database programmatically with a driver (e.g., PyMongo in Python) instead of the shell — same lazy creation concept, but code-based.
- Deploy on MongoDB Atlas instead of local install for a managed, cloud-hosted database with a free tier.
Real-world use cases
- Store user profiles in a
userscollection for a web app, with flexible fields like optionalroleoravatar. - Log IoT sensor readings into a
readingscollection, leveraginginsertManyfor bulk ingestion from devices. - Kick off a content management system with
postsandcommentscollections, allowing different fields per document as schemas evolve.
Key takeaways
- A MongoDB database is a container for collections, and collections hold documents (BSON objects).
- Databases and collections are created lazily — they don't exist until you insert data.
- Use
use <dbName>to switch or create a database, andinsertOneto start adding data. insertManyis efficient for bulk inserts, butinsertOneis clearer for single records.- Verify creation with
show dbsandshow collectionsto confirm your structure. - Local installs, Atlas, and Docker are all viable ways to run MongoDB — choose based on your needs.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.