Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

MongoDB: CRUD, indexing and aggregation

Practical study notes on using MongoDB for CRUD (Create, Read, Update, Delete), how indexes work and how to write aggregation pipelines, aimed at engineering exam preparation.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

MongoDB is a popular document-oriented NoSQL database used by engineers when data is semi-structured or schema changes often. Knowing CRUD operations, how indexes speed up queries, and how to use the aggregation pipeline lets you build efficient read/write features and analytics in web and backend systems.

Key ideas

  • CRUD — stands for Create, Read, Update, Delete. These are the basic operations to manipulate documents.

  • _id — every document has a unique primary key field _id. If you do not provide _id, MongoDB creates an ObjectId automatically.

  • Index — a data structure that improves query performance. An index stores a mapping from indexed field values to the locations of documents that contain those values. Common index types in MongoDB: single-field, compound, multikey, text, hashed, TTL. TTL indexes expire documents based on a Date field and the expireAfterSeconds option.

    • Exact definition: An index is an ordered structure that supports efficient selection of documents matching a predicate on the indexed field(s) without scanning every document in the collection.

    • Trade-offs: Creating an index speeds up reads that can use the index but increases disk space and slows writes (insert/update/delete) because the index must be maintained. State precisely: "An index makes matching queries run in approximately O(log n + k) time for B-tree-like indexes versus O(n) for a collection scan, but each write that modifies indexed fields adds O(log n) overhead to maintain the index." (Assumes B-tree implementation and disk-based nodes.)

  • Aggregation pipeline — a sequence of staged operations that process documents and produce aggregated results, similar in purpose to SQL GROUP BY and window-like transformations. Each stage takes documents as input, transforms or filters them, and passes results to the next stage. Common stages: $match, $project, $group, $sort, $limit, $lookup, $unwind.

    • Exact behavior: The pipeline executes stages in order; output of stage i is input of stage i+1. Stage semantics are deterministic for deterministic operators (e.g., $match). $group groups documents by a key expression and computes accumulators (e.g., $sum, $avg).
  • Index selection and explain plans: MongoDB chooses an index using the query shape and available indexes. Use db.collection.find(query).explain() or db.collection.explain().find(query) to get the query plan. Draw for the exam: a diagram showing a collection, one index B-tree structure, an arrow from query predicate to index traversal, and pointer from index leaf to document or record ID. Label root, internal nodes, leaf nodes, and pointers to document locations.

  • When to index: Index fields that appear frequently in query filters, sort keys, or as join keys in $lookup. Avoid indexing fields with very low selectivity (almost same value for many documents) unless needed for sorting. For compound indexes, prefer placing equality-match fields before range-match fields. Note: hashed indexes do not support range queries or sorting; use them for equality lookups.

Formulas

db.collection.insertOne(document) — insert a single document into collection. document: BSON object.

db.collection.insertMany([doc1, doc2, ...]) — insert multiple documents.

db.collection.find(query, projection) — read documents matching query. projection is a document of fields to include/exclude. Note: you cannot mix inclusion and exclusion in the same projection (except for _id).

db.collection.updateOne(filter, update, options) — update first document matching filter. update uses update operators like $set, $inc. Use { upsert: true } in options to insert a new document if none matches.

db.collection.updateMany(filter, update, options) — update all documents matching filter. Supports { upsert: true } to insert if no document matches.

db.collection.deleteOne(filter) — delete first matching document.

db.collection.deleteMany(filter) — delete all matching documents.

db.collection.createIndex({ field: 1, ... }, options) — create an index on one or more fields; 1 for ascending, -1 for descending.

db.collection.dropIndex(indexName) — drop an index.

db.collection.aggregate([ stage1, stage2, ... ]) — run an aggregation pipeline composed of stage documents such as { $match: {...} }, { $group: { _id: keyExpr, total: { $sum: "$amount" } } }.

db.collection.find(query).explain('executionStats') — show query plan and stats. Allowed verbosity values include 'queryPlanner', 'executionStats', and 'allPlansExecution'.

Complexity statements (assume B-tree index and n documents):

Collection scan cost = O(n) — must check each document.

Index lookup cost ≈ O(log n) + k — cost to find the key in the index plus k to fetch k matching documents.

Worked examples

Example 1 — CRUD: insert, find, update, delete

Code (mongosh):

use shopDB // switch to database shopDB

db.products.insertMany([ { "_id": 1, "name": "pen", "price": 10, "stock": 100 }, { "_id": 2, "name": "notebook", "price": 40, "stock": 200 }, { "_id": 3, "name": "eraser", "price": 5, "stock": 500 } ])

Query: find products priced <= 10

db.products.find({ price: { $lte: 10 } }).toArray()

Exact output (formatted via toArray()):

[ { "_id": 1, "name": "pen", "price": 10, "stock": 100 }, { "_id": 3, "name": "eraser", "price": 5, "stock": 500 } ]

Update: increase price of pen by 2

db.products.updateOne({ _id: 1 }, { $inc: { price: 2 } })

Confirm:

db.products.findOne({ _id: 1 }) -> { "_id": 1, "name": "pen", "price": 12, "stock": 100 }

Delete: remove eraser

db.products.deleteOne({ _id: 3 })

Confirm remaining:

db.products.find().toArray() -> [ { "_id": 1, "name": "pen", "price": 12, "stock": 100 }, { "_id": 2, "name": "notebook", "price": 40, "stock": 200 } ]

Example 2 — Indexing: single-field and compound

Create an index on price and another compound index on { name: 1, price: -1 }.

db.products.createIndex({ price: 1 }) -> returns index name "price_1".

db.products.createIndex({ name: 1, price: -1 }) -> returns "name_1_price_-1".

Explain why: queries that filter or sort on price can use the first index. A query that filters by name and sorts by price can use the compound index.

Example 3 — Aggregation pipeline: total sales per product

Assume collection orders with sample documents:

db.orders.insertMany([ { "_id": 101, "productId": 1, "qty": 3, "price": 10, "date": ISODate("2026-03-01") }, { "_id": 102, "productId": 2, "qty": 1, "price": 40, "date": ISODate("2026-03-02") }, { "_id": 103, "productId": 1, "qty": 2, "price": 10, "date": ISODate("2026-03-05") } ])

Pipeline to compute total revenue per product:

db.orders.aggregate([ { $group: { _id: "$productId", totalRevenue: { $sum: { $multiply: ["$qty", "$price"] } }, totalQty: { $sum: "$qty" } } }, { $sort: { totalRevenue: -1 } } ]).toArray()

Exact output (formatted via toArray()):

[ { "_id": 1, "totalRevenue": 50, "totalQty": 5 }, { "_id": 2, "totalRevenue": 40, "totalQty": 1 } ]

Explanation: For productId 1: revenue = (310)+(210) = 50.

Common mistakes

  • Creating too many indexes or indexing low-selectivity fields; this increases write cost and disk usage.

  • Assuming index will be used if fields in the query do not match the index prefix for compound indexes. For a compound index on { a:1, b:1 }, queries must use a (the prefix) to use the index efficiently.

  • Not running explain() to confirm index usage; relying on intuition about which index MongoDB picks.

  • In aggregation, using $project incorrectly and losing needed fields before $group (order matters).

For your exam

Typical question types:

  • Definitions and short notes: define Document, Collection, Index, Aggregation Pipeline, explain trade-offs of indexing.

  • Hands-on queries: write MongoDB shell commands to insert, update, delete, and query with projection and sort.

  • Index design: given query patterns, propose indexes and justify choices, include effect on read/write.

  • Aggregation problems: compute grouped aggregates using pipeline stages; show stage-by-stage transformation.

What a full-marks answer includes:

  • Correct definitions with bold term usage and explanation of why it matters.

  • Exact MongoDB commands for CRUD or index creation when asked; correct use of update operators and aggregation stage order.

  • For index questions, state complexity difference (O(n) vs O(log n + k)), explain prefix rule for compound indexes, and discuss write overhead.

  • For aggregation, provide complete pipeline, describe what each stage does, and compute expected output for given data.

Quick check

  1. What MongoDB command creates a compound index on fields city (ascending) and age (descending)?
  2. Which aggregation stage removes fields and can rename fields in output documents?
  3. For a B-tree-like index, what is the typical complexity to locate matching keys versus a full collection scan?

Answers: 1. db.collection.createIndex({ city: 1, age: -1 }). 2. $project. 3. Index lookup ≈ O(log n) + k; collection scan = O(n).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?