Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 70 ยท Practice and wrap-up

Practice: Query and Update Exercises

Twenty hands-on MongoDB exercises on find, comparison and logical operators, arrays, sorting, pagination and updates, each with a full runnable solution.

You learn MongoDB queries the way you learn to ride a bike: by doing them until your hands know the shapes. This lesson gives you twenty exercises on one small collection of films, covering filters, operators, arrays, sorting, pagination and updates. Fourteen are queries, six are updates, and each has a complete solution that runs right here.

The code runs on the tutorial's practice engine, a plain JavaScript stand-in (see The Practice Engine Used in This Tutorial). Filters and updates are exactly the documents you would type in mongosh; only the plumbing around them differs. For a shell, replace movies.find(filter) with db.movies.find(filter).

How to use this page

Read the task Look at the data first.
Write your filter Edit the TryIt and replace the solution.
Run and compare Check your result against ours.
Explain the difference Different result? Find out why.

Do not peek at the solutions before trying. Struggling is the point.

1 / 2

The data

Ten films. Each has title, year, an array of genres, a numeric rating (the last film has none, on purpose), runtime in minutes, a nested director object with name and country, a cast array, a views counter and an array of reviews, each { user, score }. "Untitled Project" lacks rating and runtime; that missing data is there to catch careless filters. Every TryIt on this page starts by recreating the same collection, so you can edit any exercise on its own.

Part 1: queries (exercises 1 to 14)

  1. Find every film released in 2001.
  2. List the titles (only the title, no _id) of films rated 8.5 or higher.
  3. Find films released from 1999 to 2008, both years included. Show titles.
  4. Find the films tagged sci-fi.
  5. Find the films tagged both sci-fi and drama.
  6. Find the films whose director comes from the UK (the country is inside the director subdocument).
  7. Find the films that have no rating field at all.
  8. Find films that are longer than 140 minutes or rated below 8.
  9. Find films whose genres include neither action nor animation.
  10. Find films whose title starts with "The".
  11. Find films with exactly three cast members.
  12. Show the three best-rated films, best first, with only title and rating.
  13. Films sorted by year ascending, three per page: show page 2.
  14. Find films reviewed by ana with a score of 9 or more. One review must satisfy both conditions.

Take a few minutes with these before reading on. The solutions follow in one runnable block. Each line prints the exercise number and the answer, so you can compare it with what you wrote.

JS Exercises 1 to 14: solutions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What the solutions teach

Four of these exercises hide a trap, and they are worth a second look.

Exercise 8 does not return "Untitled Project", although that film has no runtime and no rating. A missing field never satisfies a range comparison such as $gt or $lt, so neither branch of the $or matches it. That is also why exercise 7 needs $exists: false: you cannot find missing data with a comparison. See Element and Evaluation Operators.

Exercise 9 uses $nin on an array field. $nin means "no element of the array is in this list", so a film with ["action", "crime", "drama"] is excluded because one genre matches. People often expect $ne to mean "has some genre other than X". It does not: { genres: { $ne: "action" } } also excludes every film that has action anywhere in the array.

Exercise 12 sorts by rating descending. Real MongoDB sorts a missing value as the lowest, so films without a rating come last in descending order. Always combine sort with limit in this order: sort first, then cut.

Exercise 14 needs $elemMatch. Without it, { "reviews.user": "ana", "reviews.score": { $gte: 9 } } asks for some review by ana and some, possibly different, review scoring 9 or more. $elemMatch forces both conditions onto the same array element. Compare it with Array Query Operators if the difference is still fuzzy.

Also note exercise 13: pagination with skip is fine for small pages, but see Sorting, Limiting and Skipping for why deep pages should use a range filter instead.

Part 2: updates (exercises 15 to 20)

  1. Mark "Amelie" as featured by adding the field featured: true.
  2. Add 1000 views to every sci-fi film in one command.
  3. Remove the views field from "The Room".
  4. Add a new review { user: "sam", score: 8 } to "Arrival".
  5. Add the genre mystery to "Arrival" without creating a duplicate, and run it twice to see what the result reports.
  6. Update the film "Dune" so that its year is 2021, creating it with views: 0 if it does not exist yet.

Each update prints its result object, so you can read matchedCount, modifiedCount and upsertedId. After the updates, the block checks the data with a read query.

JS Exercises 15 to 20: solutions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What the update solutions teach

Exercise 16 is the lesson about updateMany: one command changed every matching film, and matchedCount equals modifiedCount because each one really changed. $inc also creates a missing field with the increment as its value, so a film without views would end up with 1000.

Exercise 17: $unset takes any value (the stand-in and the real server ignore it); the convention is "" or 1. Unsetting a field that does not exist matches but modifies nothing.

Exercise 19 shows the difference between "matched" and "modified". The second run finds "Arrival" (matchedCount: 1) but mystery is already in the set, so nothing changes (modifiedCount: 0). Never treat modifiedCount: 0 as an error; it can simply mean "already in the desired state". Compare Updating Arrays for $push versus $addToSet.

Exercise 20 combines $set and $setOnInsert with upsert: true. The first call finds no "Dune", so it creates one containing the fields from the filter (title), the $set field (year) and the $setOnInsert field (views), and the result carries an upsertedId. The second call matches the film it just created and, because $setOnInsert applies only on insert and year is unchanged, modifies nothing. See Upserts, Replace and findAndModify.

In the stand-in, a new document gets the counter _id 11. Real MongoDB would generate an ObjectId.

Part 3: cinema booking exercises

The first two parts used one collection. Real applications have several that refer to each other, so this third set uses a small cinema booking data model with four collections: movies, theaters, users and bookings. The exercises run from beginner (create an index, filter) to advanced (top-N, revenue per theater, "who has not booked"). For each one, try to write the mongosh command yourself before reading ours.

The mongosh solutions are real MongoDB syntax and cannot run on this page. The TryIt that follows runs the same questions with plain JavaScript helpers (group, lookup, sortBy) over the same sample data, so you can check the answers your command should return.

The documents look like this:

JavaScript
// movies
{ _id: 1, title: "Last Orbit", genre: "scifi", durationMin: 128, rating: 8.6 }
// theaters
{ _id: 1, name: "Central", city: "Berlin", screens: 3 }
// users
{ _id: 1, name: "Ann", city: "Berlin", joined: ISODate("2025-01-10") }
// bookings: one document per booking; the price is stored per seat
{ _id: 1, userId: 1, movieId: 1, theaterId: 1, seats: 2, pricePerSeat: 12, date: ISODate("2026-02-14") }

Beginner

Exercise 21. Prepare the collections. Create indexes that the later queries need: bookings are looked up by user and by movie, and movies by genre.

JavaScript
db.bookings.createIndex({ userId: 1, date: -1 })
db.bookings.createIndex({ movieId: 1 })
db.movies.createIndex({ genre: 1, rating: -1 })

A compound index with the equality field first and the sort field second serves "a user's latest bookings" with no extra sort (see Compound Index Design).

Exercise 22. Good science fiction. List the titles of scifi movies rated 8 or higher, best first.

JavaScript
db.movies.find({ genre: "scifi", rating: { $gte: 8 } }, { title: 1, rating: 1, _id: 0 }).sort({ rating: -1 })

Exercise 23. Big bookings. Find bookings of at least 4 seats at a price per seat below 15.

JavaScript
db.bookings.find({ seats: { $gte: 4 }, pricePerSeat: { $lt: 15 } })

Intermediate

Exercise 24. Seats per movie. Count the total seats booked per movie id, most seats first.

JavaScript
db.bookings.aggregate([
  { $group: { _id: "$movieId", seats: { $sum: "$seats" } } },
  { $sort: { seats: -1 } }
])

Exercise 25. Revenue per theater. Revenue is seats * pricePerSeat. Show each theater's name and revenue, highest first.

JavaScript
db.bookings.aggregate([
  { $group: { _id: "$theaterId", revenue: { $sum: { $multiply: ["$seats", "$pricePerSeat"] } } } },
  { $lookup: { from: "theaters", localField: "_id", foreignField: "_id", as: "theater" } },
  { $unwind: "$theater" },
  { $project: { _id: 0, theater: "$theater.name", revenue: 1 } },
  { $sort: { revenue: -1 } }
])

Advanced

Exercise 26. Top two movies by revenue. Join the movie title, and return only the two best earners.

JavaScript
db.bookings.aggregate([
  { $group: { _id: "$movieId", revenue: { $sum: { $multiply: ["$seats", "$pricePerSeat"] } } } },
  { $sort: { revenue: -1 } },
  { $limit: 2 },
  { $lookup: { from: "movies", localField: "_id", foreignField: "_id", as: "movie" } },
  { $unwind: "$movie" },
  { $project: { _id: 0, title: "$movie.title", revenue: 1 } }
])

Putting $sort and $limit before the $lookup means only two joins happen instead of one per movie, which is the main performance habit of the pipeline (see Aggregation Performance).

Exercise 27. Users who have never booked. Return the names of users with no booking at all.

JavaScript
db.users.aggregate([
  { $lookup: { from: "bookings", localField: "_id", foreignField: "userId", as: "bookings" } },
  { $match: { bookings: { $size: 0 } } },
  { $project: { _id: 0, name: 1 } }
])
// or, with two simple queries:
const bookedIds = db.bookings.distinct("userId")
db.users.find({ _id: { $nin: bookedIds } }, { name: 1, _id: 0 })

The "not booked" question is an anti-join: keep the left rows that have no match on the right. The $lookup plus empty-array check works; for a large bookings collection the two-query version with distinct and $nin is often simpler, provided the id list stays small.

Exercise 28. Customers in a different city. List users who booked in a theater located in a city other than their own.

JavaScript
db.bookings.aggregate([
  { $lookup: { from: "users", localField: "userId", foreignField: "_id", as: "user" } },
  { $lookup: { from: "theaters", localField: "theaterId", foreignField: "_id", as: "theater" } },
  { $unwind: "$user" },
  { $unwind: "$theater" },
  { $match: { $expr: { $ne: ["$user.city", "$theater.city"] } } },
  { $group: { _id: "$user.name", cities: { $addToSet: "$theater.city" } } }
])

Run the helpers below to see the answers each command should return. Compare them with what you get on a real server, then change the data and predict how the answers change.

JS Check your answers: the cinema bookings data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What the cinema exercises teach

  • Index design follows the query: equality fields first, then the sort field, and an index for every foreign key you $lookup on.
  • Revenue is a computed value. Because it comes from seats * pricePerSeat, put the multiplication inside the $sum; you need not store the total (though storing it, as in the schema design patterns, speeds up reports).
  • Top-N queries: $group, then $sort, then $limit, and only then $lookup, so you join just the winners.
  • Anti-joins (users without bookings) are $lookup with an empty-array test, or $nin with a distinct list.
  • Comparing two fields from different collections needs a join first and $expr afterwards.

If any of these felt heavy, revisit Lookup and Joins and Group Stage, then come back and try the pipelines again without peeking.

How to practise beyond this page

Good practice is variation. Take any exercise and change one thing: a different country, a different threshold, reversed sort order. Predict the output before you run it, then run it. When your prediction is wrong, you have found exactly the gap in your mental model, which is the most valuable thing a practice session can produce.

Next, try rewriting a few exercises as mongosh commands from memory, then compare them with the real syntax in the earlier lessons. Finally, move on to pipelines in Practice: Aggregation Exercises.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which filter finds films where the SAME review is by ana and scores 9 or more?

    $elemMatch applies all its conditions to one array element. The dot-notation version can be satisfied by two different reviews.
  2. 2. A film has no rating field. Does { rating: { $lt: 8 } } match it?

    Missing fields never satisfy $lt, $gt and friends. Use $exists: false to find them.
  3. 3. An updateOne with $addToSet reports matchedCount 1 and modifiedCount 0. What happened?

    modifiedCount counts documents that actually changed. $addToSet leaves an array alone when the value is already present.
  4. 4. What does { upsert: true } do when no document matches the filter?

    An upsert creates one document from the equality conditions in the filter and applies the update operators; $setOnInsert fields apply only in that case.

Summary

  • Twenty exercises covered equality, ranges, $or, $nin, $regex, $size, $all, $elemMatch, dot paths, projection, sort, skip and limit.
  • Range operators never match a missing field; use $exists for that.
  • $ne and $nin on arrays exclude a document if any element matches.
  • $elemMatch keeps several conditions on one array element.
  • updateMany, $inc, $unset, $push, $addToSet and upserts report their effect through matchedCount, modifiedCount and upsertedId.
  • Predict, run, compare: that loop is how query skills grow.

Continue with Practice: Aggregation Exercises.