Database · MongoDB · 2026
MongoDB Basics Explained for Beginners
Quick summary — MongoDB basics for beginners
MongoDB is a document database: instead of rows and tables, it
stores data as flexible JSON-like documents inside collections.
A document is one record — a product, a user, an order — and it
can contain nested objects and arrays. A collection is a group of
documents, roughly like a table. The big difference from SQL is
that documents in the same collection do not have to share an
identical schema, and you can embed related data directly instead
of joining across tables. You interact with MongoDB through CRUD
operations — insertOne, find,
updateOne, deleteOne — plus query
operators ($gt, $in,
$and) and indexes that keep queries fast. For a
beginner, the whole game is: learn the data model, learn CRUD,
learn a handful of operators, learn when to embed vs reference,
and add indexes to the fields you actually query. That is a 2–3
week investment with a very high payoff.
In this guide you will learn:
- What MongoDB is and why it exists — and when it beats SQL.
- Documents, collections, and BSON — the data model in plain English.
- CRUD operations — the four commands you will use every day.
- Query operators, projections, and indexes — how to ask real questions and keep them fast.
- Schema design — embedding vs referencing, and common beginner mistakes.
SECTION 01What MongoDB is and why it exists
MongoDB is an open-source document database. Instead of storing rows in tables with a fixed set of columns, it stores documents — JSON-like structures that can hold nested objects, arrays, and mixed types. Documents live inside collections, and collections live inside databases. That is the whole hierarchy: database → collection → document.
It exists because modern applications often need to store data whose shape changes quickly. A product catalog might start with three fields and grow to thirty. A user profile might need a new array of preferences. In a relational database, each change is a migration; in MongoDB, you can just start writing the new shape and handle the old documents in code. That flexibility is the main reason teams reach for it.
| SQL World | MongoDB World |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| Primary key | _id field (auto-generated) |
| JOIN | Embedding or $lookup |
SECTION 02Documents, collections, and BSON
A document is a single record. It is written in a JSON-like syntax, but stored on disk in a binary format called BSON (Binary JSON). BSON supports more types than plain JSON — dates, ObjectIds, binary data, and 64-bit integers — which is why MongoDB can store real application data without converting everything to strings.
A collection is a group of documents. Unlike a SQL table, the
documents inside a collection do not have to share an identical
schema. One product document can have a discount field
and another can have a warranty field, and MongoDB will
happily store both. That is the "flexible schema" people talk about.
// One document inside the "products" collection.
// Notice the nesting — no JOIN needed to read the whole product.
{
"_id": ObjectId("66d4f1c2a8b3e4f5d6c7b8a9"),
"name": "Wireless Mouse",
"price": 799,
"category": "electronics",
"tags": ["wireless", "usb", "ergonomic"],
"specs": {
"connectivity": "2.4 GHz",
"battery": "AA",
"buttons": 3
},
"inStock": true,
"createdAt": ISODate("2026-09-01T10:15:00Z")
}
// _id is the primary key — MongoDB generates it automatically
// if you do not supply one. It is unique per collection.
// A user document with an embedded address object.
// Embedding keeps reads fast: one find() returns the whole user.
{
"_id": ObjectId("66d4f1c2a8b3e4f5d6c7b8aa"),
"name": "Priya Sharma",
"email": "priya@example.com",
"address": {
"line1": "12 MG Road",
"city": "Bengaluru",
"state": "Karnataka",
"pincode": "560001"
},
"roles": ["customer", "reviewer"],
"createdAt": ISODate("2026-08-14T06:30:00Z")
}
// You can query into nested fields with dot notation:
// db.users.find({ "address.city": "Bengaluru" })
// You can also index them:
// db.users.createIndex({ "address.city": 1 })
// Documents in the same collection do NOT need the same shape.
// This is valid — and often the right choice in MongoDB.
// Document 1: a product with a discount
{
"_id": ObjectId("...01"),
"name": "Wireless Mouse",
"price": 799,
"discount": { "type": "percent", "value": 10 }
}
// Document 2: a product with warranty info instead
{
"_id": ObjectId("...02"),
"name": "Mechanical Keyboard",
"price": 2499,
"warranty": { "months": 24, "provider": "BrandCare" }
}
// Document 3: a product with both
{
"_id": ObjectId("...03"),
"name": "USB-C Hub",
"price": 1499,
"discount": { "type": "flat", "value": 200 },
"warranty": { "months": 12, "provider": "HubCare" }
}
// This is flexibility, not chaos — your application code decides
// which fields are required for which kinds of product.
SECTION 03CRUD operations — the four core commands
Every MongoDB operation you will do as a beginner is one of four things: create a document, read documents, update a document, or delete a document. Learn these four and you can build most of a working application.
| Operation | Command | What It Does |
|---|---|---|
| Create | insertOne / insertMany |
Add one or many documents |
| Read | find / findOne |
Retrieve documents matching a filter |
| Update | updateOne / updateMany |
Change fields on existing documents |
| Delete | deleteOne / deleteMany |
Remove documents matching a filter |
// MongoDB CRUD — the four operations you will use every day.
// Run these in mongosh against a local database.
// Use (or create) a database and collection
use shop
// CREATE — insert a single document
db.products.insertOne({
name: "Wireless Mouse",
price: 799,
category: "electronics",
tags: ["wireless", "usb"],
inStock: true,
createdAt: new Date()
})
// CREATE — insert many documents at once
db.products.insertMany([
{ name: "Mechanical Keyboard", price: 2499, category: "electronics", inStock: true },
{ name: "USB-C Hub", price: 1499, category: "electronics", inStock: false }
])
// READ — find documents that match a filter
db.products.find({ category: "electronics" })
// READ — find a single document
db.products.findOne({ name: "Wireless Mouse" })
// UPDATE — change one field on one document
db.products.updateOne(
{ name: "Wireless Mouse" },
{ $set: { price: 699 } }
)
// UPDATE — increment a numeric field
db.products.updateOne(
{ name: "Mechanical Keyboard" },
{ $inc: { price: 100 } }
)
// DELETE — remove one document
db.products.deleteOne({ name: "USB-C Hub" })
// DELETE — remove many documents
db.products.deleteMany({ category: "electronics", inStock: false })
// Query operators, projections, and sort — the tools you need
// to ask real questions of your data.
// Comparison operators
db.products.find({ price: { $gt: 500 } })
db.products.find({ price: { $gte: 500, $lte: 2000 } })
db.products.find({ category: { $in: ["electronics", "accessories"] } })
// Logical operators
db.products.find({
$and: [
{ category: "electronics" },
{ inStock: true }
]
})
db.products.find({
$or: [
{ price: { $lt: 500 } },
{ inStock: false }
]
})
// Existence and type
db.products.find({ tags: { $exists: true } })
db.products.find({ price: { $type: "number" } })
// Projection — return only the fields you need
db.products.find(
{ category: "electronics" },
{ name: 1, price: 1, _id: 0 }
)
// Sort, limit, skip — pagination
db.products
.find({ category: "electronics" })
.sort({ price: -1 })
.limit(10)
.skip(0)
// Count matching documents
db.products.countDocuments({ inStock: true })
// Distinct values — useful for filters in a UI
db.products.distinct("category")
// Indexes and explain — how to make queries fast and prove it.
// See what indexes already exist
db.products.getIndexes()
// Single-field index on a field you filter or sort by
db.products.createIndex({ category: 1 })
// Compound index — matches queries that filter on both fields
db.products.createIndex({ category: 1, price: -1 })
// Unique index — enforce uniqueness
db.users.createIndex({ email: 1 }, { unique: true })
// TTL index — auto-delete old sessions
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
// Text index — basic full-text search
db.products.createIndex({ name: "text", description: "text" })
db.products.find({ $text: { $search: "wireless keyboard" } })
// explain() — check whether the query uses the index
db.products
.find({ category: "electronics", price: { $gt: 500 } })
.explain("executionStats")
// Look for:
// stage: "IXSCAN" — index used (good)
// stage: "COLLSCAN" — full collection scan (slow)
// totalDocsExamined — should be close to nReturned
// Rule of thumb: index every field you filter or sort by
// in production queries. Do not index everything — writes pay
// the cost of every index you add.
insertOne, find with a filter and
projection, updateOne with $set, and why
an index exists, you are already ahead of most candidates.
SECTION 04Query operators, projections, and indexes
Once CRUD feels natural, the next step is asking better questions. Query operators let you filter by range, membership, existence, and logic. Projections let you return only the fields you need. Indexes make the whole thing fast.
| Skill | What It Means | Priority |
|---|---|---|
| Comparison operators | $gt, $gte, $lt, $lte, $in |
Essential |
| Logical operators | $and, $or, $not |
Essential |
| Projections | Return only name and price, skip the rest |
Essential |
| Sort, limit, skip | Pagination and ordering for real UIs | High |
| Single-field index | createIndex({ category: 1 }) |
Essential |
| Compound index | createIndex({ category: 1, price: -1 }) |
High |
| explain() | Prove a query uses the index instead of scanning | High |
| Text index | Basic full-text search on string fields | Medium |
| TTL index | Auto-expire old sessions or logs | Medium |
find() filter or sort(). If a
query does a COLLSCAN in explain(), add an
index or rewrite the query. If it does an IXSCAN, you
are done.
SECTION 05Schema design — embedding vs referencing
This is the one topic that separates beginners who "know the commands" from beginners who can actually design a database. In MongoDB, you have two ways to model a relationship:
| Approach | When to Use It | Example |
|---|---|---|
| Embedding | One-to-few, and the data is read together | Order with its line items inside the same document |
| Referencing | One-to-many, many-to-many, or the data is large | Blog post referencing an authorId |
| Hybrid | Embed a summary, reference the full record | Order embeds product name + price, references productId |
find(). If a
screen needs data from two collections, ask whether embedding would
let you fetch it in one read. That is the whole trick.
SECTION 06Common beginner mistakes
These are the mistakes almost every beginner makes. Knowing them in advance saves you weeks of debugging.
| Mistake | The Reality |
|---|---|
| "MongoDB has no schema." | It has a flexible schema. You still define the shape — you just do it in your application or with a JSON Schema validator. |
| "Normalize everything like SQL." | MongoDB is designed for embedding. Splitting a read-together object into three collections adds lookups for no reason. |
| "Indexes slow everything down." | Indexes speed up reads and add a small write cost. Index deliberately — the fields you actually filter and sort by. |
| "Unbounded arrays are fine." | Documents have a 16 MB limit. Arrays that grow forever will hit it. Use bucketing or referencing for large lists. |
| "Return the whole document every time." | Projections exist for a reason. Return only the fields the screen needs — it is faster and cheaper. |
SECTION 07Interview Q&A — MongoDB basics
Q1What is MongoDB and how is it different from SQL?
MongoDB is a document database. It stores JSON-like documents in collections instead of rows in tables. The key differences are: the schema is flexible (documents in one collection can have different fields), related data can be embedded in a single document instead of joined across tables, and the query language is JavaScript-based rather than SQL.
Q2What is the difference between a document and a collection?
A document is a single record — one product, one user, one order. A collection is a group of documents, roughly like a table. A database holds one or more collections. So the hierarchy is: database → collection → document.
Q3When should you embed vs reference?
Embed when the data is one-to-few and is read together — for
example, an order with its line items. Reference when the data
is one-to-many, many-to-many, or large enough that embedding
would bloat the document. A useful hybrid is to embed a
denormalized summary (name, price) and reference the full
record by _id.
Q4Why do indexes matter, and how do you know one is being used?
Without an index, MongoDB scans every document in a collection
to find matches (COLLSCAN). With an index, it jumps
directly to the matching documents (IXSCAN). Use
explain("executionStats") to see which plan the
query uses — if you see COLLSCAN, add an index or
rewrite the query.
Q5What are the four CRUD operations, and when do you use each?
Create (insertOne, insertMany) when
adding new data. Read (find, findOne)
when querying. Update (updateOne,
updateMany) when changing existing documents.
Delete (deleteOne, deleteMany) when
removing data. In practice, most of your code is read and
update — writes are rarer.
SECTION 08Test yourself — MongoDB basics
Five questions. No sign-up.
0 / 5Pick an answer to see why it is right or wrong.
SECTION 09Frequently asked questions
What is MongoDB used for?
MongoDB is used for applications that need flexible, rapidly evolving data — product catalogs, user profiles, content management, real-time analytics, and mobile backends. It is especially common in JavaScript and Python stacks where the application already works with JSON.
Is MongoDB better than SQL?
Not "better" — different. MongoDB is a strong fit when your data shape changes often or when reads naturally map to whole documents. SQL is a strong fit when you need strict schemas, complex joins, or multi-table transactions. Most modern teams use both.
Do I need to know SQL to learn MongoDB?
No. MongoDB has its own query language, and beginners can learn it without SQL. That said, understanding basic database concepts — primary keys, indexes, transactions — helps a lot, and most backend roles will expect some SQL too.
How long does it take to learn MongoDB basics?
At 5–6 hours per week, most beginners can learn enough MongoDB to build a small application in 2–3 weeks. Focus on the data model, CRUD, a handful of query operators, and schema design — not on every feature the database offers.
What is the difference between embedding and referencing?
Embedding stores related data inside the same document — fast to
read, good for one-to-few. Referencing stores a link (usually an
_id) to another document — good for one-to-many and
many-to-many. Choose based on how the application reads the
data, not on database purity.
SECTION 10Related reads
Classroom & online · Noida
Learn MongoDB basics — with Uncodemy
Our MongoDB Training Course covers documents and collections, CRUD operations, query operators, indexes, schema design, and connecting to a Node.js or Python backend. Built for beginners who want to work with real data.
₹25,000 · full programme- CRUD + queries
- Indexes & schema design
- Node.js & Python drivers
- Weekday & weekend batches