Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

MongoDB Documentation

A document database that stores JSON-like data — CRUD, aggregation and indexing (the M in MERN).

MongoDB is a document database: instead of rows in tables it stores flexible, JSON-like documents (BSON) in collections. A document can contain arrays and nested objects, so data that belongs together is stored together. It's the "M" in the MERN stack and works naturally with JavaScript and Node.js through Mongoose.

1. Introduction & Installation

  • Easiest: a free cluster on MongoDB Atlas — add your IP under Network Access and copy the connection string.
  • Local: install MongoDB Community Server and mongosh (the shell), or Docker: docker run -p 27017:27017 mongo:7.
  • GUI: MongoDB Compass.
mongosh "mongodb://localhost:27017"                       # local
mongosh "mongodb+srv://user:pass@cluster0.xxxxx.mongodb.net/school"   # Atlas
SQL term MongoDB term
database database
table collection
row document
column field
primary key _id (auto ObjectId if you don't give one)
JOIN embedding or $lookup
show dbs
use school          // switches (creates on first write)
show collections

⚠️ Common error: MongoServerSelectionError: connection timed out with Atlas — your IP isn't on the Network Access list (add it, or 0.0.0.0/0 for testing).

2. Documents & Data Types

Documents look like JSON but support more types (BSON): String, Number (int/double/NumberDecimal), Boolean, Date, ObjectId, Array, embedded Object, null.

All examples on this page use this sample data (run it once in mongosh):

// Sample data: students and courses
db.students.insertMany([
  { _id: 1, name: "Asha",  city: "Pune",   marks: 91, skills: ["js", "react"],   address: { pin: "411001", state: "MH" } },
  { _id: 2, name: "Ravi",  city: "Delhi",  marks: 78, skills: ["java"],          address: { pin: "110001", state: "DL" } },
  { _id: 3, name: "Neha",  city: "Pune",   marks: 85, skills: ["python", "js"],  address: { pin: "411002", state: "MH" } },
  { _id: 4, name: "Kabir", city: "Mumbai", marks: 66, skills: [],                address: { pin: "400001", state: "MH" } },
  { _id: 5, name: "Isha",  city: "Delhi",  marks: 92, skills: ["cpp", "python"], address: { pin: "110002", state: "DL" } }
])
db.courses.insertMany([
  { _id: "dsa",   title: "DSA in C++",   students: [1, 3, 5], fee: 0 },
  { _id: "react", title: "React Basics", students: [1, 3],    fee: 499 }
])
db.students.findOne({ _id: 1 })

Output:

{
  _id: 1,
  name: 'Asha',
  city: 'Pune',
  marks: 91,
  skills: [ 'js', 'react' ],
  address: { pin: '411001', state: 'MH' }
}

⚠️ Common error: documents in a collection can have different shapes. That's flexible but risky — validate with Mongoose schemas or MongoDB's $jsonSchema validator.

3. Create: Inserting Documents

db.students.insertOne({ _id: 6, name: "Meera", city: "Pune", marks: 88, skills: ["go"] })
db.students.countDocuments()
{ acknowledged: true, insertedId: 6 }
6

If you omit _id, MongoDB generates an ObjectId like ObjectId('66f0c1a2...'), which also encodes the creation time. insertMany accepts { ordered: false } to continue after a duplicate-key error.

⚠️ Common error: E11000 duplicate key error — a document with the same _id (or another unique index value) already exists.

4. Read: Querying with find()

db.students.find({ city: "Pune" }, { _id: 0, name: 1, marks: 1 })
db.students.find({ marks: { $gte: 80, $lt: 92 } }, { name: 1 })
db.students.find({ city: { $in: ["Delhi", "Mumbai"] } }).sort({ marks: -1 }).limit(2).projection({ _id: 0, name: 1, marks: 1 })
[ { name: 'Asha', marks: 91 }, { name: 'Neha', marks: 85 } ]
[ { _id: 1, name: 'Asha' }, { _id: 3, name: 'Neha' } ]
[ { name: 'Isha', marks: 92 }, { name: 'Ravi', marks: 78 } ]
Operator Meaning
$eq $ne $gt $gte $lt $lte comparisons
$in / $nin value in / not in a list
$and $or $not $nor logical
$exists field present or not
$regex pattern match
$all, $size, $elemMatch arrays
db.students.find({ $or: [{ marks: { $gt: 90 } }, { city: "Mumbai" }] }, { _id: 0, name: 1 })
db.students.find({ skills: "js" }, { _id: 0, name: 1 })                  // array contains "js"
db.students.find({ "address.state": "DL" }, { _id: 0, name: 1 })         // nested field (quotes!)
db.students.find({ skills: { $size: 0 } }, { _id: 0, name: 1 })
db.students.find({ name: { $regex: "^[AI]" } }, { _id: 0, name: 1 })
[ { name: 'Asha' }, { name: 'Kabir' }, { name: 'Isha' } ]
[ { name: 'Asha' }, { name: 'Neha' } ]
[ { name: 'Ravi' }, { name: 'Isha' } ]
[ { name: 'Kabir' } ]
[ { name: 'Asha' }, { name: 'Isha' } ]

⚠️ Common error: without a projection, find() returns whole documents — slow for large ones. Ask only for the fields you need.

5. Update: Changing Documents

db.students.updateOne({ _id: 2 }, { $set: { city: "Noida" }, $inc: { marks: 5 } })
db.students.updateOne({ _id: 4 }, { $push: { skills: "sql" } })
db.students.updateMany({ city: "Pune" }, { $addToSet: { skills: "js" } })    // no duplicates
db.students.find({ _id: { $in: [2, 4, 3] } }, { name: 1, city: 1, marks: 1, skills: 1 })
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 2,
  modifiedCount: 0,
  upsertedCount: 0
}
[
  {
    _id: 2,
    name: 'Ravi',
    city: 'Noida',
    marks: 83,
    skills: [ 'java' ]
  },
  {
    _id: 3,
    name: 'Neha',
    city: 'Pune',
    marks: 85,
    skills: [ 'python', 'js' ]
  },
  {
    _id: 4,
    name: 'Kabir',
    city: 'Mumbai',
    marks: 66,
    skills: [ 'sql' ]
  }
]

(Both Pune students already had "js", so $addToSet modified 0 documents.)

Update operators: $set, $unset, $inc, $mul, $rename, $min/$max, $push, $pull, $addToSet, $pop, and $ / $[] for array elements. Use { upsert: true } to insert when nothing matches.

⚠️ Common error: updateOne({ _id: 2 }, { city: "Noida" }) (no $set) throws "Update document requires atomic operators". To replace a whole document use replaceOne.

6. Delete

db.students.deleteOne({ _id: 4 })
db.students.deleteMany({ marks: { $lt: 80 } })
db.students.countDocuments()
{ acknowledged: true, deletedCount: 1 }
{ acknowledged: true, deletedCount: 1 }
3

db.collection.drop() removes a whole collection; db.dropDatabase() removes the current database.

⚠️ Common error: deleteMany({}) with an empty filter deletes every document. Run the same filter with find() first.

7. Aggregation Pipeline

The aggregation pipeline passes documents through stages — like Unix pipes for data.

db.students.aggregate([
  { $match: { marks: { $gte: 70 } } },
  { $group: { _id: "$city", count: { $sum: 1 }, avgMarks: { $avg: "$marks" }, names: { $push: "$name" } } },
  { $sort: { avgMarks: -1 } }
])
[
  { _id: 'Pune', count: 2, avgMarks: 88, names: [ 'Asha', 'Neha' ] },
  { _id: 'Delhi', count: 2, avgMarks: 85, names: [ 'Ravi', 'Isha' ] }
]
db.students.aggregate([
  { $unwind: "$skills" },                                   // one document per array element
  { $group: { _id: "$skills", students: { $sum: 1 } } },
  { $sort: { students: -1, _id: 1 } },
  { $limit: 3 }
])

db.students.aggregate([
  { $project: { _id: 0, name: 1, grade: { $cond: [{ $gte: ["$marks", 90] }, "A", "B"] }, skillCount: { $size: "$skills" } } },
  { $match: { grade: "A" } }
])
[
  { _id: 'js', students: 2 },
  { _id: 'python', students: 2 },
  { _id: 'cpp', students: 1 }
]

[
  { name: 'Asha', grade: 'A', skillCount: 2 },
  { name: 'Isha', grade: 'A', skillCount: 2 }
]

Joins with $lookup:

db.courses.aggregate([
  { $lookup: { from: "students", localField: "students", foreignField: "_id", as: "enrolled" } },
  { $project: { _id: 0, title: 1, learners: { $size: "$enrolled" },
                names: { $sortArray: { input: "$enrolled.name", sortBy: 1 } } } }   // $lookup order isn't guaranteed
])
[
  {
    title: 'DSA in C++',
    learners: 3,
    names: [ 'Asha', 'Isha', 'Neha' ]
  },
  { title: 'React Basics', learners: 2, names: [ 'Asha', 'Neha' ] }
]

Other useful stages: $addFields, $facet (several pipelines at once — e.g. results + total count), $bucket, $sortByCount, $out/$merge (write results to a collection), $skip.

⚠️ Common error: putting $match late in the pipeline. Filter as early as possible so fewer documents flow through (and indexes can be used).

8. Indexing

db.students.createIndex({ city: 1, marks: -1 })        // compound index
db.students.createIndex({ name: 1 }, { unique: true })
db.students.getIndexes().map((i) => i.name)
db.students.find({ city: "Pune" }).sort({ marks: -1 }).explain("executionStats").executionStats.totalDocsExamined
city_1_marks_-1
name_1
[ '_id_', 'city_1_marks_-1', 'name_1' ]
2

Only the 2 Pune documents were examined — the index did the work. Without an index the plan shows COLLSCAN (reads every document) instead of IXSCAN.

Index types: single field, compound (order matters — ESR rule: Equality, Sort, Range), multikey (arrays), text, geospatial (2dsphere), TTL (auto-delete after a time), partial and unique.

⚠️ Common error: adding indexes for everything — each index slows down writes and uses RAM. Index the fields your frequent queries filter and sort on.

9. Data Modelling

The golden rule: design for how the app reads the data.

  • Embed when data is read together and owned by one parent (address in a user, items in an order, comments if few).
  • Reference (store ids) when data is shared, very large, or grows without limit (a user's 10,000 posts).
  • A document can't exceed 16 MB.
// Embedded: one read gets the order with its items
{ _id: 101, customer: "Asha", items: [ { sku: "BOOK-1", qty: 2, price: 450 } ], total: 900 }

// Referenced: posts point to the author
{ _id: "p1", title: "Learning MongoDB", authorId: 1 }

Schema validation on the server:

db.createCollection("users", {
  validator: { $jsonSchema: {
    bsonType: "object",
    required: ["email", "name"],
    properties: { email: { bsonType: "string", pattern: "@" }, age: { bsonType: "int", minimum: 13 } }
  } }
})

10. Advanced Concepts: Mongoose, Transactions & More

Mongoose (Node.js ODM) adds schemas, validation and helpers:

import mongoose from "mongoose";
await mongoose.connect(process.env.MONGO_URI);

const studentSchema = new mongoose.Schema(
  {
    name: { type: String, required: true, trim: true },
    email: { type: String, required: true, unique: true, lowercase: true },
    marks: { type: Number, min: 0, max: 100, default: 0 },
    skills: [String],
    course: { type: mongoose.Schema.Types.ObjectId, ref: "Course" },
  },
  { timestamps: true }                                 // adds createdAt / updatedAt
);
studentSchema.index({ marks: -1 });
const Student = mongoose.model("Student", studentSchema);

await Student.create({ name: "Asha", email: "ASHA@example.com", marks: 91 });
const toppers = await Student.find({ marks: { $gte: 85 } })
  .select("name marks")
  .sort({ marks: -1 })
  .limit(10)
  .populate("course", "title")                         // fill the referenced course
  .lean();                                             // plain objects, faster
await Student.updateOne({ email: "asha@example.com" }, { $inc: { marks: 2 } });

Pagination — skip is fine for small offsets; for big collections use a range on an indexed field ("load more"):

const page = await Student.find({ _id: { $gt: lastSeenId } }).sort({ _id: 1 }).limit(20);

Transactions (replica set / Atlas required) — all-or-nothing across documents:

const session = await mongoose.startSession();
await session.withTransaction(async () => {
  await Account.updateOne({ _id: from }, { $inc: { balance: -500 } }, { session });
  await Account.updateOne({ _id: to }, { $inc: { balance: 500 } }, { session });
});
session.endSession();

Also learn: change streams (real-time updates), Atlas Search, time-series collections, replica sets (high availability) and sharding (horizontal scaling), and security — never build queries from raw user objects (use express-mongo-sanitize to block $ operator injection).

11. Examples with Output

Example 1 — Top 3 students with a rank-style label

db.students.find({}, { _id: 0, name: 1, marks: 1 }).sort({ marks: -1 }).limit(3)
[
  { name: 'Isha', marks: 92 },
  { name: 'Asha', marks: 91 },
  { name: 'Neha', marks: 85 }
]

Example 2 — Count and average per state with $facet (two reports in one query)

db.students.aggregate([
  { $facet: {
      byState: [{ $group: { _id: "$address.state", n: { $sum: 1 } } }, { $sort: { _id: 1 } }],
      overall: [{ $group: { _id: null, avg: { $avg: "$marks" }, max: { $max: "$marks" } } }, { $project: { _id: 0 } }]
  } }
])
[
  {
    byState: [ { _id: 'DL', n: 2 }, { _id: 'MH', n: 3 } ],
    overall: [ { avg: 82.4, max: 92 } ]
  }
]

Example 3 — Upsert a visit counter

db.visits.updateOne({ _id: "home" }, { $inc: { count: 1 } }, { upsert: true })
db.visits.updateOne({ _id: "home" }, { $inc: { count: 1 } }, { upsert: true })
db.visits.findOne({ _id: "home" })
{
  acknowledged: true,
  insertedId: 'home',
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 1
}
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
{ _id: 'home', count: 2 }

12. Practice Problems

Use the sample data above:

  1. Find students from Maharashtra (address.state: "MH") with marks above 80, showing only name and city.
  2. Add the skill "git" to every student who doesn't have it.
  3. Rename the field marks to score for all documents.
  4. Count students per skill and show the most common skill.
  5. Use $lookup to list each course with the names of its students, sorted by number of students.
  6. Create the right index for "students in a city sorted by marks" and confirm IXSCAN with explain().
  7. Model a blog (users, posts, comments) — decide what to embed and what to reference, and justify it.
  8. Build an Express + Mongoose API with paginated GET /students?page=2&limit=10.

13. Interview Questions

1. SQL vs NoSQL (MongoDB)? SQL databases use fixed schemas, tables and joins with strong relational integrity. MongoDB stores flexible documents, scales horizontally easily and suits evolving or nested data.

2. What is _id and ObjectId? Every document's unique primary key. ObjectId is a 12-byte default value containing a timestamp, a random value and a counter.

3. Embedding vs referencing? Embed data that is read together and bounded in size; reference data that is shared, large or unbounded.

4. What is the aggregation pipeline? A sequence of stages ($match, $group, $project, $lookup, $sort...) that transform documents to produce analytics and reports.

5. How do indexes work in MongoDB? B-tree structures on fields; queries using them do an IXSCAN instead of a COLLSCAN. Compound index order matters (Equality → Sort → Range).

6. Does MongoDB support transactions? Yes — multi-document ACID transactions on replica sets and sharded clusters (since 4.0/4.2).

7. What is a replica set and sharding? A replica set is a group of servers with copies of the data (automatic failover). Sharding splits data across servers by a shard key for horizontal scaling.

8. find() vs aggregate()? find() filters and projects documents; aggregate() can also group, join, reshape and compute new fields.

9. What does Mongoose add? Schemas, validation, defaults, middleware (hooks), population of references and a convenient model API.

10. What is NoSQL injection? Sending objects like { "$gt": "" } in user input to change a query's meaning. Prevent it by validating/sanitising input and casting types.

14. Cheat Sheet & References

Shell basics

// databases and collections
show dbs; use school; show collections; db.dropDatabase()
db.createCollection("logs"); db.logs.drop()

CRUD

db.c.insertOne({ name: "A" }); db.c.insertMany([{ a: 1 }, { a: 2 }])
db.c.find({ age: { $gte: 18 } }, { name: 1, _id: 0 }).sort({ age: -1 }).skip(10).limit(5)
db.c.findOne({ _id: id }); db.c.countDocuments({ city: "Pune" }); db.c.distinct("city")
db.c.updateOne({ _id: id }, { $set: { a: 1 }, $inc: { n: 1 } }); db.c.updateMany(f, { $unset: { tmp: "" } })
db.c.updateOne(f, { $push: { tags: "x" } }, { upsert: true }); db.c.replaceOne(f, doc)
db.c.deleteOne({ _id: id }); db.c.deleteMany({ done: true })

Query operators

{ a: { $in: [1, 2] } }; { a: { $exists: true } }; { $or: [{ a: 1 }, { b: 2 }] }
{ tags: "js" }; { tags: { $all: ["a", "b"] } }; { items: { $elemMatch: { qty: { $gt: 5 } } } }
{ "address.city": "Pune" }; { name: { $regex: "^a", $options: "i" } }

Aggregation

db.c.aggregate([{ $match: {} }, { $group: { _id: "$city", n: { $sum: 1 }, avg: { $avg: "$m" } } }, { $sort: { n: -1 } }])
{ $project: { name: 1, total: { $add: ["$a", "$b"] } } }; { $unwind: "$tags" }; { $limit: 10 }
{ $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } }

Indexes

db.c.createIndex({ city: 1, marks: -1 }); db.c.createIndex({ email: 1 }, { unique: true })
db.c.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }); db.c.getIndexes()
db.c.find(f).explain("executionStats")

Mongoose

const User = mongoose.model("User", new mongoose.Schema({ name: { type: String, required: true } }, { timestamps: true }));
await User.create(doc); await User.find(f).select("name").sort({ createdAt: -1 }).limit(10).lean();
await User.findById(id).populate("posts"); await User.findByIdAndUpdate(id, { $set: d }, { new: true });

Official documentation