MongoDB flashcards
Store data as flexible JSON-like documents.
Beginner friendly, starts from zero
0
MongoDB at a glance
MongoDB is a database that stores an app's information as documents that look like filled-in forms.
A filing cabinet: the database is the cabinet, collections are drawers, documents are forms and fields are lines on each form.
Words you will meet
- Document
- One record, written in curly braces with fields and values
- Field
- A named piece of a document, like name or city
- Collection
- A group of similar documents, like all orders
- BSON
- MongoDB's binary form of JSON that also knows dates and exact numbers
- _id
- The unique label every document has
- Filter
- A description of which documents you want back
- Driver
- The code library your app uses to talk to the database
- Index
- A sorted lookup list that makes searches fast
The steps
- 1. Start from zero (12 cards): What a database is, how MongoDB stores documents, and the words the rest of the topic uses.
- 2. Core basics (16 cards): Documents, collections, mongosh and the CRUD calls you use every day.
- 3. Next steps (16 cards): Arrays, indexes, explain, aggregation and modelling choices you make weekly.
- 4. Go deeper (16 cards): Replica sets, consistency, transactions, sharding and tuning in production.
All 12 cards in Start from zero
- What is MongoDB, in one plain sentence?
- MongoDB is a database: a program that stores an app's information safely and finds it again fast. It keeps each record as a document that looks like a filled-in form.
- What problem does a database solve? What was it like before?
- Apps must remember things after you close them: accounts, orders, messages. Plain files break when thousands of people read and write at once; a database handles that safely and quickly.
- Where do you already meet a database every day?
- When a shopping app shows your past orders, a chat app loads old messages, or a game keeps your score, a database answered. MongoDB runs behind many such apps.
- What everyday thing is MongoDB like?
- A filing cabinet. The database is the cabinet, a collection is one drawer, a document is one form in the drawer, and a field is one line on that form.
- What are a document, a field and a value?
- A document is one record in curly braces. Each field is a name, like
name, paired with a value, like"Harish". Text values go in quotes; numbers do not. - What are a collection and a database?
- A collection is a group of similar documents, like all orders or all customers. A database holds several collections for one app, like a shop with orders, products and users.
- What are JSON and BSON?
- JSON is a plain text way to write data with curly braces, used all over the web. BSON is MongoDB's compact binary version of it that also knows real dates and exact money amounts.
- What is
_id? - Every document has an
_idfield: a unique label, like a roll number in a class. If you do not give one, MongoDB makes anObjectIdfor you. - First tiny win: what does this line ask the database?
findon the people collection returns every document that matches the filter. Here the filter asks for all people whose city is Chennai.- What are a shell, a driver, a cluster and a connection string?
- The shell,
mongosh, is a text window where you type database commands. A driver is the code library your app uses. A cluster is a group of database servers, reached by its address, the connection string. - What do you need before you start?
- A free MongoDB Atlas cloud database made in your browser, or MongoDB on your own computer, plus the
mongoshshell. Knowing a little JSON helps; nothing else is needed. - What will you be able to do after this topic?
- Store and change documents, write filters to find exactly what you need, sort and page results, speed up searches with indexes, and design collections for a real app.
MongoDB cheatsheet
CRUD
insertMany(docs, { ordered: false })Fast bulk insertfind(filter, { name: 1, _id: 0 })Query with projectionupdateOne(f, { $set: {...} })Change named fields onlyupdateOne(f, u, { upsert: true })Update or insertfindOneAndUpdate(f, u, { returnDocument: "after" })Update and get the new docdeleteMany({ expiresAt: { $lt: now } })Remove matchesbulkWrite([...], { ordered: false })Mixed batch of writescountDocuments(f) / estimatedDocumentCount()Exact vs quick count
Query operators
{ total: { $gte: 500, $lt: 2000 } }Range{ status: { $in: ["paid", "shipped"] } }Any of a list{ "address.city": "Pune" }Nested field{ items: { $elemMatch: {...} } }One element, all rules{ phone: { $exists: true } }Field present{ age: { $type: "string" } }Find wrong types{ $expr: { $gt: ["$spent", "$budget"] } }Compare two fields
Update operators
$set / $unsetSet or remove fields$inc: { views: 1 }Atomic counter$setOnInsertOnly when upsert inserts$addToSet / $pullAdd unique / remove from array$push: { log: { $each: [x], $slice: -50 } }Capped array"items.$[i].qty" + arrayFiltersUpdate matching array itemsupdateMany(f, [ { $set: {...} } ])Pipeline update with expressions
Aggregation
$matchFilter, put first$group: { _id: "$city", n: { $sum: 1 } }Group and total$lookupLeft join another collection$unwind: "$items"One doc per array item$project / $setShape or add fields$sort + $limitTop N, merged into one step$facetSeveral results in one pass$merge / $outWrite results to a collection
Indexes and ops
createIndex({ status: 1, createdAt: -1, total: 1 })ESR compound index{ unique: true, partialFilterExpression: {...} }Unique for some docs{ expireAfterSeconds: 3600 }TTL index.explain("executionStats")IXSCANorCOLLSCAN, docs examineddb.orders.aggregate([{ $indexStats: {} }])Find unused indexesdb.currentOp({ secs_running: { $gte: 5 } })Long-running operationsrs.status()Replica set health