MongoDB essentials: 50 cards on queries, indexes and aggregation
MongoDB basics: documents and BSON, CRUD in mongosh, query operators, indexes, the aggregation pipeline, embedding vs referencing, replica sets and sharding.
Practice now
Study without an account
Scheduled with the default Askesis timings. Progress is saved in this browser.
All 50 cards
- 1What is a MongoDB document?A record of field–value pairs, like a JSON object, that can nest objects and arrays; it is stored as BSON
- 2What is BSON?Binary JSON: the binary format MongoDB stores documents in. It adds types JSON lacks, like
ObjectId,Date,Decimal128, 32- and 64-bit integers and binary data - 3Maximum size of a single document16 MB. Store larger files with GridFS, and keep documents from growing without limit
- 4What is special about the
_idfield?It is every document’s primary key: unique in the collection, immutable, automatically indexed, and generated as anObjectIdif you don’t supply one - 5What is inside an
ObjectId?12 bytes: a 4-byte timestamp in seconds, a 5-byte random value and a 3-byte counter, so IDs roughly sort by creation timeid.getTimestamp()returns the creation date. - 6What is a collection?A group of documents, similar to a table but with no fixed schema by default; it is created automatically on the first insert
- 7Enforce a schema on a collectionjs
db.createCollection('users', { validator: { $jsonSchema: { bsonType: 'object', required: ['email'], properties: { email: { bsonType: 'string' } }, }, }, })Add a validator to an existing collection withcollMod. - 8Insert one and several documentsjs
db.users.insertOne({ name: 'Ada', age: 36 }) db.users.insertMany([{ name: 'Alan' }, { name: 'Grace' }]) - 9What does this return?js
db.users.find( { age: { $gte: 18 } }, { name: 1, email: 1, _id: 0 }, )The name and email (without_id) of every user aged 18 or over: the first argument filters, the second is a projection - 10Can a projection mix
1and0?No, except for_id: either list the fields to include or the fields to exclude - 11What does
find()return?A cursor that fetches results in batches; iterate it, or call.toArray()in a drivermongosh prints the first 20 documents; typeitfor more. - 12What does this return?js
db.posts.find().sort({ createdAt: -1 }).limit(10)The ten newest posts:-1sorts descending,1ascendingPaging with largeskip()values gets slow; filter on an indexed field instead, likecreatedAt < lastSeen. - 13Change one field of a documentjs
db.users.updateOne({ _id: id }, { $set: { email: '[email protected]' } }) - 14What happens here?js
db.users.updateOne({ _id: id }, { email: '[email protected]' })It throws: update documents must use operators like$set. To replace a whole document on purpose, usereplaceOne - 15Common update operators
$setsets fields,$unsetremoves them,$incadds to a number,$pushappends to an array,$addToSetappends only if absent,$pullremoves matching elements - 16What does
upsert: truedo?Updates the matching document, or inserts a new one built from the filter and the update if nothing matchesjsdb.stats.updateOne({ day: '2026-10-15' }, { $inc: { views: 1 } }, { upsert: true }) - 17
deleteOnevsdeleteManydeleteOneremoves the first matching document;deleteManyremoves all matches, anddeleteMany({})empties the collection - 18MongoDB comparison operators
$eq,$ne,$gt,$gte,$lt,$lte,$inand$ninjsdb.orders.find({ status: { $in: ['paid', 'shipped'] } }) - 19Why does this ignore the lower bound?js
db.users.find({ age: { $gt: 18 }, age: { $lt: 30 } })A JavaScript object can’t have twoagekeys, so the second replaces the first. Combine them:{ age: { $gt: 18, $lt: 30 } } - 20What does this match?js
db.users.find({ $or: [{ role: 'admin' }, { age: { $gte: 65 } }] })Users who are admins or at least 65. Listing several fields in one filter, without$or, means AND - 21Query a field inside an embedded documentUse quoted dot notation:
{ 'address.city': 'Paris' }Without quotes,address.cityas a key is a JavaScript syntax error. - 22What does
{ tags: 'mongodb' }match whentagsis an array?Every document whosetagsarray contains'mongodb'{ tags: ['a', 'b'] }matches only that exact array in that order; use$allfor “contains both”. - 23Why use
$elemMatch?To require a single array element to meet every condition.{ scores: { $gte: 80, $lt: 90 } }can match with one element ≥ 80 and a different one < 90jsdb.students.find({ scores: { $elemMatch: { $gte: 80, $lt: 90 } } }) - 24What does
{ phone: null }match?Documents wherephoneis null and documents with nophonefield at all; use{ phone: { $exists: false } }for missing only - 25Which extra documents does
{ status: { $ne: 'banned' } }return?Documents that have nostatusfield at all;$neand$ninmatch missing fields too - 26
countDocumentsvsestimatedDocumentCountcountDocuments(filter)counts matching documents exactly;estimatedDocumentCount()returns the whole collection’s count from metadata, much faster - 27Create a unique index on
emailjsdb.users.createIndex({ email: 1 }, { unique: true })1is ascending and-1descending; direction matters mostly for compound sorts. - 28The ESR rule for compound indexesOrder fields as Equality, then Sort, then Range: fields matched exactly first, sort fields next, range filters like
$gtlast - 29Which queries can use an index on
{ a: 1, b: 1, c: 1 }?Queries on its prefixes:a,aandb, or all three. A query onborcalone can’t use it efficiently - 30What is a multikey index?An index on an array field: MongoDB indexes every element automatically. A compound index can include at most one array field per document
- 31Delete sessions an hour after creationjs
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })A TTL index needs a date field. A background task removes expired documents about every 60 seconds, so deletion isn’t instant. - 32How do you check whether a query uses an index?Run
.explain('executionStats'):IXSCANmeans an index scan,COLLSCANa full collection scan. ComparetotalDocsExaminedwithnReturned - 33What is the aggregation pipeline?An array of stages, such as
$match,$group,$sortand$project, where each stage transforms the documents and passes them to the next - 34Total paid order amounts per customer, largest firstjs
db.orders.aggregate([ { $match: { status: 'paid' } }, { $group: { _id: '$customerId', total: { $sum: '$amount' }, orders: { $sum: 1 } } }, { $sort: { total: -1 } }, ]) - 35Why put
$matchas early as possible in a pipeline?It shrinks the data every later stage processes, and a$matchat the start of the pipeline can use indexes - 36Join orders with their usersjs
{ $lookup: { from: 'users', localField: 'userId', foreignField: '_id', as: 'user' } }$lookupis a left outer join within the same database;useris always an array. - 37What does
{ $unwind: '$tags' }do?Outputs one copy of the document per element oftags, withtagsset to that element; often used after$lookup - 38
'$amount'vs'amount'in an aggregation expression'$amount'is a field path that reads each document’samount;'amount'is just the literal string - 39
$projectvs$addFields$projectreshapes documents, keeping only what you list (plus_id);$addFields(alias$set) keeps every field and adds or overwrites some - 40
$outvs$mergeBoth write pipeline results to a collection and must be the last stage:$outreplaces the target collection,$mergeinserts or updates into it - 41When should you embed related data?When it is read together with its parent, belongs to it, and stays small and bounded, like a user’s addresses or an order’s line items
- 42When should you reference another document instead?When the related data is large or unbounded, shared by many documents (many-to-many), or read and updated on its own
- 43Why are ever-growing arrays an anti-pattern?An array that grows without limit, like every comment on a post, slows updates and indexes and eventually hits the 16 MB document limit
- 44Are MongoDB writes atomic?A write to a single document is atomic, including its embedded documents. Multi-document ACID transactions exist (since 4.0) but cost more, so model data to need them rarely
- 45What is a replica set?A group of servers holding the same data: one primary takes writes, secondaries copy its oplog, and if the primary fails the others elect a new one
- 46Why should a replica set have at least three members?Electing a primary needs a majority of voting members. With three, losing one still leaves a majority; with two, losing either leaves no primary
- 47What is the catch with reading from secondaries?Replication is asynchronous, so a read preference like
secondaryPreferredcan return stale data - 48What does write concern
w: 'majority'mean?The write is acknowledged only after most voting members have it, so it survives a primary failover; it is the default since MongoDB 5.0 in most deployments - 49What is sharding?Horizontal scaling: a collection is split across shards by a shard key,
mongosrouters send each query to the right shards, and config servers hold the metadataEach shard is itself a replica set. - 50What makes a bad shard key?A steadily increasing value like a timestamp (with ranged sharding, every insert hits one shard), low cardinality, or a field most queries don’t filter on (scatter-gather queries)Hashed sharding spreads monotonically increasing keys across shards.
Frequently asked questions
Which syntax do the examples use?
mongosh, the MongoDB shell, which is JavaScript. The Node.js driver uses the same method names and query documents, so the cards carry over directly.
Should I embed or reference related data?
Embed data that is read with its parent and stays bounded, like an order’s items. Reference data that is large, unbounded or shared, like a user’s orders or many-to-many relations.
Does MongoDB support transactions?
Yes. Single-document writes are always atomic, and multi-document ACID transactions are available on replica sets and sharded clusters, though a good schema needs them rarely.
More in Databases
SQL
Learn SQL that holds up in production: joins, grouping, NULL semantics, indexes, transactions, window functions and CTEs.
50 cardsPostgreSQL
PostgreSQL know-how: data types, B-tree and GIN indexes, EXPLAIN, isolation levels, MVCC and VACUUM, JSONB, CTEs, window functions, constraints and roles.
50 cardsRedis
Redis basics: strings, lists, sets, sorted sets, hashes and streams, TTLs, RDB and AOF persistence, pub/sub, caching patterns, eviction and MULTI/EXEC.
50 cards