MongoDB & NoSQL — Rapid Revision 1■■ NoSQL Basics & CAP Theorem NoSQL = Not Only
SQL
• Non-relational, schema-free, distributed, scalable.
• Types: Key-Value, Document, Column, Graph.
• MongoDB = Document-oriented.
CAP Theorem
C – Consistency (same data everywhere)
A – Availability (system keeps working)
P – Partition Tolerance (works despite network splits)
→ You can have only 2 of 3 (AP or CP).
BASE vs ACID
SQL (ACID) → strict consistency
NoSQL (BASE) → Basically Available, Soft state, Eventual consistency
Eventual Consistency: All copies sync up after some time.
2■■ MongoDB Basics & Data Model MongoDB = Open-source, document-oriented NoSQL DB
storing JSON-like documents.
Mapping:
Table → Collection
Row → Document
Column → Field
Primary Key → _id
• _id: 12 bytes (timestamp + machine ID + process ID + counter)
• Stored in BSON (Binary JSON)
• No fixed schema, joins, or constraints
• Max document size = 16 MB
3■■ CRUD Operations CREATE
db.students.insertOne({ name: "Alice", age: 21 })
db.students.insertMany([{ name: "Bob" }, { name: "Geeta" }])
READ
db.students.find()
db.students.find({ name: "Alice" })
db.students.find({ $or: [{ name: "Bob" }, { age: 21 }] })
db.students.find({}, { name: 1, city: 1, _id: 0 })
UPDATE
db.students.updateOne({ name: "Geeta" }, { $set: { city: "Bombay" } })
db.students.updateMany({ city: "Delhi" }, { $set: { state: "Delhi NCR" } })
DELETE
db.students.deleteOne({ name: "Bob" })
db.students.deleteMany({ age: { $gt: 20 } })
Sort / Limit / Skip
.sort({ city: 1 }) Ascending
.sort({ city: -1 }) Descending
.limit(2), .skip(2)
4■■ Aggregation & Operators Pipeline Stages:
$match – filter
$group – group & count
$sort – sort
$project – show/hide fields
$limit / $skip – restrict results
$unwind – split arrays
$lookup – join collections
$lookup Example:
db.students.aggregate([
{ $lookup: { from: "marks", localField: "_id", foreignField: "student_id", as: "student_marks" } } ])
Common Operators:
Comparison – $eq, $gt, $lt, $in, $nin
Logical – $and, $or, $not, $nor
Array – $all, $size, $elemMatch
Update – $set, $unset, $inc, $push, $addToSet, $pull
■ Top 10 Exam Questions 1. What is NoSQL? How does it differ from relational DBs?
2. Explain CAP theorem with examples.
3. What are BASE properties?
4. Define MongoDB and its key features.
5. Explain how _id works.
6. Write MongoDB queries for insert, read, update, delete.
7. What is BSON?
8. Explain $match, $group, and $project.
9. Difference between $push and $addToSet.
10. Purpose of $lookup and its SQL equivalent.