What Is MongoDB?

Understand what MongoDB is and why it exists. This lesson explains MongoDB's purpose as a NoSQL document database, its benefits, use cases, and how it fits into modern applications. A hands-on exercise and next steps are included.

Focus: understand what mongodb is and why it exists

Sponsored

Every day, teams abandon the rigid world of SQL tables for a database that stores data the way your application already thinks about it: as JSON-like documents. MongoDB exists because the relational model, while powerful, forces you to contort your objects into rows and columns, fight schema migrations, and scale horizontally only with painful effort. If you've ever felt the pain of a JOIN that should be a simple lookup, or a schema change that brings your deployment to a halt, this lesson will show you why MongoDB was built and why it has become the database of choice for millions of developers.

The problem this lesson solves

Traditional relational databases (like MySQL, PostgreSQL, or SQL Server) have been the default for decades. They store data in tables with fixed rows and columns, and they enforce a schema — a strict definition of what each row must contain. For many applications, this works fine. But as software development evolved, the friction became impossible to ignore:

  • Object-relational impedance mismatch — The objects in your code (dicts in Python, objects in JavaScript) don't map cleanly to tables. You spend hours writing mapping layers like ORMs just to translate between two different data models.
  • Schema migrations are painful — Changing a column type or adding a new field requires ALTER TABLE, which can lock large tables and cause downtime. Rolling out a new feature mid-migration is a nightmare.
  • Horizontal scaling is difficult — Relational databases traditionally scale vertically (bigger machines), which gets expensive fast. Sharding relational data across many servers is complex and often requires application-level changes.
  • Semi-structured data is hard to store — Think of a blog post with optional tags, a user with a dynamic list of preferences, or a product catalog with varying attributes. In SQL, you'd either create sparse rows with lots of NULL values or use complex joins to a secondary table.

MongoDB was created to solve these exact pains. It's a document database that stores data as flexible, JSON-like documents, and it was designed from the ground up for developer productivity and horizontal scalability.

Core concept / mental model

Think of MongoDB as a warehouse of filing cabinets — but instead of rigid spreadsheet-like tables, you have folders (collections) that contain paper forms (documents). Each form can have a different shape: one form for a customer might have a phone field, another might not; one product might have a color attribute, another might have size. You don't need to pre-print the form; you just write whatever fields you need — JSON style — and the warehouse accepts it.

More formally, MongoDB uses:

  • Database — the top-level container (like a schema in SQL)
  • Collection — a group of documents (comparable to a table, but schema-less)
  • Document — a single record stored as BSON (Binary JSON), which is basically JSON with a few extra data types

The beauty is that a document naturally maps to a dictionary in Python or an object in JavaScript — no ORM required. When you fetch a document, it's already in a shape you can use directly in your code.

Here's a visual model to keep in mind:

Database: online_shop
  └── Collection: users
        ├── Document 1: { "name": "Alice", "age": 30, "email": "alice@example.com" }
        └── Document 2: { "name": "Bob", "age": 25 }  // no email field — totally fine!

How it works step by step

Let's walk through the core workflow of MongoDB — from starting a server to querying data:

  1. Install and start MongoDB — Install the MongoDB Community Server on your machine, or use a cloud service like MongoDB Atlas. Once installed, start the mongod daemon. It listens on port 27017 by default.
  2. Connect to the server — Use a client like the mongosh shell or a driver in your favorite language (Python's pymongo, Node.js's mongoose, etc.). You connect to a specific database — if it doesn't exist, MongoDB creates it the first time you write data.
  3. Create a collection — Collections are created implicitly when you insert your first document. No need to define a schema!
  4. Insert documents — Each document is a JSON-like object. You can have as many fields as you want — they don't have to match other documents in the collection.
  5. Query the data — Use the find() method with a filter to retrieve documents that match your conditions.
  6. Update and delete — Modify documents with methods like updateOne() or delete with deleteOne(). You can even add new fields on the fly.

The key is flexibility: the database adapts to your data rather than forcing your data to fit the database. That's why MongoDB is often called schema-less, though we'll see later that optional schema validation is available when you need it.

Hands-on walkthrough

Let's get you hands-on with MongoDB. We'll use the mongosh shell for simplicity — you can follow along with any driver later. We'll simulate a simple user profile system to demonstrate the flexibility.

First, start mongosh (or install MongoDB if you haven't yet). Then:

# Start mongosh and connect to the local MongoDB instance
mongosh

Create a database and insert a couple of documents with different shapes:

// Switch to (create) the 'my_database' database
use my_database

// Insert a user with many fields
db.users.insertOne({
  name: "Alice",
  age: 30,
  email: "alice@example.com",
  address: {
    street: "123 Main St",
    city: "Springfield"
  },
  tags: ["developer", "blogger"]
})

// Insert another user with only a name — no email, no address
db.users.insertOne({
  name: "Bob",
  age: 25
})

Now query all users:

// Find all documents in the users collection
db.users.find().pretty()

You'll see both documents — each with its own structure. Notice how Bob doesn't have an email or address — that's perfectly valid in MongoDB.

Pro tip: Use pretty() in the shell to format the output so it's easier to read.

To query only users older than 26:

db.users.find({ age: { $gt: 26 } })

This returns just Alice. The $gt operator means "greater than".

These examples show the core idea: you insert any JSON-like object, query it flexibly, and the database handles it. No CREATE TABLE, no migrations.

Compare options / when to choose what

MongoDB is one of many database types. It's important to understand when to pick it over alternatives. Here's a quick comparison:

Feature MongoDB (document) PostgreSQL (relational) Redis (key-value)
Data model Flexible documents Rigid tables Key-value pairs
Schema Schema-less (optional validation) Strict schema None
Query language Rich JSON-based queries SQL Limited (key lookups)
Scaling Horizontal (sharding) built-in Mostly vertical (sharding complex) Horizontal (clustering)
Best for Rapid prototyping, semi-structured data, high write throughput Complex queries, transactions, strict data integrity Caching, session storage, real-time leaderboards
Transactions Multi-document ACID (since 4.0) Full ACID Limited (multi-key transactions from 4.0)

As a rule of thumb:

  • Choose MongoDB when your data is document-like, you need flexible schemas, or you plan to scale horizontally.
  • Choose a relational database when you need complex joins, enforce strict data integrity, or your queries depend on multi-table relationships.
  • Choose Redis when you need blazing-fast reads of simple key-value pairs.

MongoDB also fits well in microservices architectures, where each service owns its data and doesn't need complex cross-service joins.

Troubleshooting & edge cases

Even as a beginner, you'll run into a few hiccups. Let's fix the most common ones:

  • connect ECONNREFUSED 127.0.0.1:27017 — This means your MongoDB server isn't running. Start it with mongod (or brew services start mongodb-community on macOS) before running mongosh.
  • Database name contains spaces — MongoDB database names can't contain spaces, /, \, ., ", *, <, >, :, |, ?, $, or null characters. Use underscores instead.
  • Insert fails with duplicate key error — This happens if you try to insert two documents with the same _id. By default, MongoDB creates an _id field with a unique ObjectId; if you specify your own _id, it must be unique.
  • Query returns nothing — Double-check your field names and value types. MongoDB is case-sensitive and type-sensitive — {"age": "30"} won't match a numeric 30.
  • mongoose model not saving a field — If using an ODM like Mongoose, you need to add the field to the schema. MongoDB itself doesn't care, but the ODM enforces a schema by default.

Pro tip: When in doubt, use db.collection.find().pretty() to inspect what your documents actually look like, and verify field names by copying them from the output.

What you learned & what's next

You now understand what MongoDB is and why it exists: it was built to solve the pains of relational databases by storing data as flexible JSON-like documents, making development faster and scaling easier. You've also done a hands-on exercise with mongosh — creating a database, inserting documents, and querying them.

Here's what you've accomplished:

  • You can explain MongoDB's role as a NoSQL document database.
  • You've seen the mental model of databases, collections, and documents.
  • You can run basic queries and handle common issues.

Next step: Now that you understand the basics, the next lesson in this track will dive into how MongoDB stores data — specifically the BSON format and the differences between collections and documents. You'll also learn to design collections that optimize for performance and readability.

Keep that mongosh open — you'll be using it in the next lesson!

Practice recap

Try this: start mongosh on your machine, create a new database called practice, insert a few documents with different fields (e.g., a book with title, author, and pages, and another with just title and price), and then query all documents. Then, explore the find({}) with a filter — say, books with more than 200 pages. This reinforces the core idea of flexible, schema-less storage.

Common mistakes

  • Thinking MongoDB is like SQL — it's not; you don't write SELECT * FROM, you use db.collection.find().
  • Treating collections like rigid tables — each document can have its own fields, and that's a feature, not a bug.
  • Forgetting that queries are type-sensitive: {"age": "30"} won't match a numeric 30.
  • Assuming you need to define a schema before inserting data — MongoDB creates collections automatically on the first insert.

Variations

  1. Use MongoDB Atlas (managed cloud service) instead of a local installation — great for production and learning without setup.
  2. Use a driver like PyMongo for Python or Mongoose for Node.js to interact with MongoDB programmatically.
  3. Enable schema validation for hybrid flexibility — you can have a loose schema but enforce rules where needed.

Real-world use cases

  • E-commerce product catalog with varying product attributes (e.g., clothing has size, electronics has warranty) — MongoDB's flexible documents handle this naturally.
  • User profiles and preferences in a social app where each user may have different optional fields like bio, location, or custom settings.
  • Real-time analytics and IoT sensor data where each reading can have different measurements and metadata, and high write throughput is needed.

Key takeaways

  • MongoDB is a NoSQL document database that stores data as flexible JSON-like documents.
  • It solves the object-relational impedance mismatch and schema migration pain of relational databases.
  • MongoDB scales horizontally with built-in sharding, making it ideal for big data applications.
  • Collections are analogous to tables but don't require a predefined schema.
  • You can start using MongoDB with just one command: mongosh created a database and collection automatically.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.