MongoDB143 exercises

MongoDB Exercises with Answers

Practise MongoDB with 143 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.

Score0/ 143

1Introduction

Read the lesson
Fill in the blankseasyIntroduction

Complete the command that switches to the shop database.

 shop
Multiple choiceeasyIntroduction

What is a collection in MongoDB most similar to in SQL?

Multiple choicemediumIntroduction

What happens if you insert a document without an _id?

Predict the outputmediumIntroduction

A collection has 3 documents. What does this return?

db.items.insertOne({ name: 'Pen' })
db.items.countDocuments()
Multiple choicehardIntroduction

Can two documents in the same collection have different fields?

Fill in the blankseasyInsert

Complete the command that adds several documents at once.

db.tags.([{ name: 'new' }, { name: 'sale' }])
Multiple choiceeasyInsert

What does insertOne return when it succeeds?

Multiple choicemediumInsert

What error does inserting a duplicate _id cause?

Predict the outputmediumInsert

How many documents are saved by this ordered insert if B already exists?

db.c.insertMany([{ _id: 'A' }, { _id: 'B' }, { _id: 'C' }])
Multiple choicehardInsert

What does { ordered: false } change in insertMany?

3Find & Queries

Read the lesson
Fill in the blankseasyFind & Queries

Complete the query to find the single user with id 7.

db.users.({ _id: 7 })
Multiple choiceeasyFind & Queries

What does find() return?

Predict the outputmediumFind & Queries

Using the products collection, how many documents does this match?

db.products.find({ category: 'kitchen', 'stock.warehouse': 'Leeds' })
Multiple choicemediumFind & Queries

What does { tags: 'sale' } match when tags is an array?

Multiple choicehardFind & Queries

What does { discount: null } match?

4Query Operators

Read the lesson
Fill in the blankseasyQuery Operators

Complete the filter to find products cheaper than 10.

db.products.find({ price: { : 10 } })
Multiple choiceeasyQuery Operators

Which operator matches any value in a list?

Predict the outputmediumQuery Operators

How many products does this match in the products collection?

db.products.countDocuments({ category: { $in: ['kitchen', 'office'] } })
Multiple choicemediumQuery Operators

How do you find documents that don't have a phone field?

Multiple choicehardQuery Operators

When do you need $elemMatch?

5Projection & Sorting

Read the lesson
Fill in the blankseasyProjection & Sorting

Complete the sort so the newest orders come first.

db.orders.find().sort({ createdAt:  })
Multiple choiceeasyProjection & Sorting

What does the projection { name: 1, _id: 0 } return?

Predict the outputmediumProjection & Sorting

With 45 matching documents and 20 per page, how many documents does page 3 return?

db.c.find().sort({ _id: 1 }).skip(40).limit(20)
Multiple choicemediumProjection & Sorting

Why add _id to a sort on price?

Multiple choicehardProjection & Sorting

Why does range-based paging stay fast when skip doesn't?

Fill in the blankseasyUpdate

Complete the update to add 1 to the views count.

db.articles.updateOne({ _id: 9 }, { : { views: 1 } })
Multiple choiceeasyUpdate

What's the difference between updateOne and updateMany?

Predict the outputmediumUpdate

A product has price 10. What are matchedCount and modifiedCount after this?

db.products.updateOne({ _id: 7 }, { $set: { price: 10 } })
Multiple choicemediumUpdate

What does { upsert: true } do?

Multiple choicehardUpdate

How can you stop stock going below zero when two customers buy at once?

Fill in the blankseasyDelete

Complete the command that removes every document with status "expired".

db.coupons.({ status: 'expired' })
Multiple choiceeasyDelete

What does deleteOne report when nothing matches?

Multiple choicemediumDelete

What does deleteMany({}) do?

Multiple choicemediumDelete

Why does findOneAndDelete suit a job queue?

Multiple choicehardDelete

What does a TTL index with expireAfterSeconds: 3600 on lastSeen do?

8Data Types

Read the lesson
Fill in the blankseasyData Types

Complete the value so the price is stored as an exact decimal.

db.products.insertOne({ name: 'Pen', price: ('1.20') })
Multiple choiceeasyData Types

What type does mongosh use for a plain number like 42?

Predict the outputmediumData Types

A collection has prices 5, '7' and 9. How many documents does this match?

db.c.countDocuments({ price: { $gt: 4 } })
Multiple choicemediumData Types

How are dates stored in MongoDB?

Multiple choicehardData Types

Which query finds documents where price is stored as text?

Fill in the blankseasyArrays

Complete the update so 'admin' is added only if it isn't already present.

db.users.updateOne({ _id: 1 }, { : { roles: 'admin' } })
Multiple choiceeasyArrays

Which operator removes elements that match a condition?

Predict the outputmediumArrays

What is tags after this update if it was ['a', 'b', 'c']?

db.c.updateOne({ _id: 1 }, { $pop: { tags: 1 } })
Multiple choicemediumArrays

What does 'items.$.qty' refer to?

Multiple choicehardArrays

How do you keep only the 10 newest entries when pushing to an array?

10Embedded Documents

Read the lesson
Fill in the blankseasyEmbedded Documents

Complete the query to find customers in Leeds using the embedded address.

db.customers.find({ '': 'Leeds' })
Multiple choiceeasyEmbedded Documents

When is embedding usually the better choice?

Multiple choicemediumEmbedded Documents

Why might you store the customer's name inside each order as well as the customer id?

Predict the outputmediumEmbedded Documents

What remains in address after this update if it was { city: 'Leeds', postcode: 'LS1' }?

db.c.updateOne({ _id: 1 }, { $set: { 'address.city': 'York' } })
Multiple choicehardEmbedded Documents

Why can embedding reduce the need for transactions?

Fill in the blankseasyIndexes

Complete the command that creates an index on email.

db.users.({ email: 1 })
Multiple choiceeasyIndexes

Which field is always indexed automatically?

Multiple choicemediumIndexes

An index is { status: 1, createdAt: -1 }. Which query can use it efficiently?

Multiple choicemediumIndexes

What does a unique index do?

Multiple choicehardIndexes

In the ESR rule, where do range fields go in a compound index?

12Aggregation Basics

Read the lesson
Fill in the blankseasyAggregation Basics

Complete the stage that keeps only paid orders.

db.orders.aggregate([{ : { status: 'paid' } }])
Multiple choiceeasyAggregation Basics

What does $group's _id decide?

Predict the outputmediumAggregation Basics

Using the sales collection, how many groups does this produce?

db.sales.aggregate([{ $group: { _id: '$month' } }])
Multiple choicemediumAggregation Basics

How do you count the documents in each group?

Multiple choicehardAggregation Basics

Why should $match usually come first?

13Aggregation Stages

Read the lesson
Fill in the blankseasyAggregation Stages

Complete the stage that turns each element of items into its own document.

db.orders.aggregate([{ : '$items' }])
Multiple choiceeasyAggregation Stages

What does $sortByCount do?

Predict the outputmediumAggregation Stages

An order with an empty items array goes through { $unwind: '$items' }. How many documents come out for it?

Multiple choicemediumAggregation Stages

What is $facet useful for?

Multiple choicehardAggregation Stages

What's the difference between $out and $merge?

14$lookup Joins

Read the lesson
Fill in the blankseasy$lookup Joins

Complete the stage name that joins another collection.

db.orders.aggregate([{ : { from: 'customers', localField: 'customerId', foreignField: '_id', as: 'customer' } }])
Multiple choiceeasy$lookup Joins

What type is the field created by $lookup's as option?

Multiple choicemedium$lookup Joins

What happens to a document with no matches in a $lookup?

Predict the outputmedium$lookup Joins

Using the sample data, how many orders does Ada's lookup array contain?

db.customers.aggregate([{ $match: { _id: 'c1' } }, { $lookup: { from: 'orders', localField: '_id', foreignField: 'customerId', as: 'o' } }, { $project: { n: { $size: '$o' } } }])
Multiple choicehard$lookup Joins

Why place $match and $limit before $lookup?

15Schema Design

Read the lesson
Fill in the blankseasySchema Design

Complete the rule of MongoDB schema design.

// Data that is accessed together should be  together.
Multiple choiceeasySchema Design

What does the computed pattern store?

Multiple choicemediumSchema Design

Which pattern keeps the five newest reviews inside a product?

Multiple choicemediumSchema Design

Why group sensor readings into hourly bucket documents?

Multiple choicehardSchema Design

What's the purpose of a schemaVersion field?

16Validation

Read the lesson
Fill in the blankseasyValidation

Complete the schema so email must always be present.

{ $jsonSchema: { : ['email'] } }
Multiple choiceeasyValidation

What happens when an insert breaks a validator with the default settings?

Multiple choicemediumValidation

Which keyword restricts a field to a list of allowed values?

Multiple choicemediumValidation

What does validationLevel: 'moderate' do?

Multiple choicehardValidation

How can you find existing documents that break a schema?

18Transactions

Read the lesson
Fill in the blankseasyTransactions

Complete the call that runs and commits a transaction.

session.(() => {
  coll.insertOne({ _id: 1 })
})
Multiple choiceeasyTransactions

Is an update that changes several fields of one document atomic?

Multiple choicemediumTransactions

What happens if the function passed to withTransaction throws?

Multiple choicemediumTransactions

What do transactions require?

Multiple choicehardTransactions

Why put the balance check in the update filter rather than reading first?

19Node.js Driver

Read the lesson
Fill in the blankseasyNode.js Driver

Complete the line that collects a cursor's documents into an array.

const docs = await products.find({ price: { $lt: 10 } }).();
Multiple choiceeasyNode.js Driver

How many MongoClient instances should a typical Node.js server create?

Multiple choicemediumNode.js Driver

Why does findOne({ _id: '64b7f3...' }) return null for an existing document?

Multiple choicemediumNode.js Driver

Which error code means a duplicate key?

Multiple choicehardNode.js Driver

How do you include an operation in a transaction with the driver?

Fill in the blankseasyMongoose

Complete the schema option that adds createdAt and updatedAt automatically.

new mongoose.Schema({ name: String }, { : true });
Multiple choiceeasyMongoose

What is Mongoose?

Multiple choicemediumMongoose

Which collection does mongoose.model('Order', schema) use by default?

Multiple choicemediumMongoose

What does .lean() do?

Multiple choicehardMongoose

What does populate('author') do?

21Performance & explain

Read the lesson
Fill in the blankseasyPerformance & explain

Complete the call to see execution statistics for a query.

db.orders.find({ status: 'open' }).explain('')
Multiple choiceeasyPerformance & explain

What does a COLLSCAN stage mean?

Multiple choicemediumPerformance & explain

A query returns 10 documents but examines 900,000. What's the likely fix?

Multiple choicemediumPerformance & explain

What makes a query covered?

Multiple choicehardPerformance & explain

What does a SORT stage above an IXSCAN suggest?

22Replication

Read the lesson
Fill in the blankseasyReplication

Complete the write concern so the write survives a failover.

db.orders.insertOne(order, { writeConcern: { w: '' } })
Multiple choiceeasyReplication

Which member of a replica set accepts writes?

Multiple choicemediumReplication

How do secondaries stay in sync with the primary?

Multiple choicemediumReplication

Why use an odd number of voting members?

Multiple choicehardReplication

What's the risk of reading from secondaries?

Fill in the blankseasySharding

Complete the command that shards the orders collection on a hashed customerId.

sh.('shop.orders', { customerId: 'hashed' })
Multiple choiceeasySharding

What does sharding do?

Multiple choicemediumSharding

Which component routes application queries to the right shards?

Multiple choicemediumSharding

Why is an always-increasing value a poor ranged shard key?

Multiple choicehardSharding

What's a scatter-gather query?

24Security & Users

Read the lesson
Fill in the blankseasySecurity & Users

Complete the role so the app can read and write the shop database.

db.createUser({ user: 'app', pwd: passwordPrompt(), roles: [{ role: '', db: 'shop' }] })
Multiple choiceeasySecurity & Users

What does least privilege mean?

Multiple choicemediumSecurity & Users

Which built-in role can read but not change data?

Multiple choicemediumSecurity & Users

Why use passwordPrompt() when creating users?

Multiple choicehardSecurity & Users

How does NoSQL injection happen?

25Backup & Monitoring

Read the lesson
Fill in the blankseasyBackup & Monitoring

Complete the command that makes a compressed logical backup.

 --uri "$URI" --db shop --gzip --archive=shop.gz
Multiple choiceeasyBackup & Monitoring

Does a replica set protect you from accidentally deleting data?

Multiple choicemediumBackup & Monitoring

Which tool restores a mongodump archive?

Multiple choicemediumBackup & Monitoring

What does RPO describe?

Multiple choicehardBackup & Monitoring

How can you recover one collection without overwriting live data?

26Null and Missing Fields

Read the lesson
Multiple choiceeasyNull and Missing Fields

After the worked $unset on contact 4, which contacts have no email field?

27Cursor Iteration and Cleanup

Read the lesson
Multiple choiceeasyCursor Iteration and Cleanup

After the worked cursor reads _id 1 with next, what does toArray return?

28Compound Keyset Pagination

Read the lesson
Multiple choiceeasyCompound Keyset Pagination

Which identifiers appear on the second main page after [5,4]?

29Bulk Writes and Partial Errors

Read the lesson

How many documents does the second worked SKU upsert bulk create?

30Optimistic Concurrency Control

Read the lesson

After the worked independent-field merge, what city remains?

31Window Functions

Read the lesson
Multiple choiceeasyWindow Functions

What rank and dense rank does score 80 receive after two tied scores of 90?

32Dates and Timezone Buckets

Read the lesson
Multiple choiceeasyDates and Timezone Buckets

Does the worked half-open daily range include the event exactly at end?

33Densify and Fill

Read the lesson
Multiple choiceeasyDensify and Fill

What value does the worked locf report show at the leading position -1?

34Read-Only Collection Views

Read the lesson
Multiple choiceeasyRead-Only Collection Views

After order 3 becomes unpaid, how many source orders remain in the worked collection?

35Materialized Summary Refresh

Read the lesson
Multiple choiceeasyMaterialized Summary Refresh

What active report is visible after building g2 but before publishing its pointer?

36Change Streams and Resume Tokens

Read the lesson

What counter value remains after the worked handler receives the same event twice?

37Time Series Collections

Read the lesson
Multiple choiceeasyTime Series Collections

Which values contribute to the practice total for the noon-to-one interval?

38GridFS File Streaming

Read the lesson
Multiple choiceeasyGridFS File Streaming

After the practice publishes version two, what does downloading oldId return?

39Geospatial Queries

Read the lesson
Multiple choiceeasyGeospatial Queries

Why does the practice return IDs 2 and 3 instead of closed ID 1?

40Multikey Index Limits

Read the lesson
Multiple choiceeasyMultikey Index Limits

Which student has one score between ninety and ninety-five inclusive?

41Collation and Index Matching

Read the lesson
Multiple choiceeasyCollation and Index Matching

Which lookup in the main fixture finds the stored Ada for lowercase ada?

42Wildcard Indexes

Read the lesson
Multiple choiceeasyWildcard Indexes

Which main-fixture product matches missing attributes.weight?

43Driver Pools and Timeouts

Read the lesson
Multiple choiceeasyDriver Pools and Timeouts

Why can the practice raise MongoServerSelectionError despite its TCP listener accepting connections?

Next steps