Querying MongoDB: find and aggregation

MongoDB's query language: filters and operators, arrays, projection, sorting, then the aggregation pipeline stage by stage.

  • 23 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Filter (find): what is it?

    Show the answer

    The first argument of a MongoDB search: a document describing the conditions the returned documents must meet.

    { annee: 2000, genres: "SF" } combines the conditions with an implicit AND; an empty filter {} returns the whole collection.

  • The films collection holds Alien (1979, genres ["SF", "Horreur"]), Matrix (1999, ["SF", "Action"]), Her (2013, ["SF", "Drame"]) and Amélie (2001, ["Comédie"]). What does db.films.find({ annee: { $gte: 2000 }, genres: "SF" }) return?

    • Her only
    • Her and Amélie
    • Alien, Matrix and Her
    • Matrix and Her
    Show the answer

    Her only

    An equality filter on an array keeps the documents whose array contains the value. Both conditions must hold: Amélie has the year but not the genre, Alien and Matrix have the genre but not the year.

  • In a pipeline, the … stage groups documents by a key and computes totals with accumulators such as ….

    Show the answer

    In a pipeline, the $group stage groups documents by a key and computes totals with accumulators such as $sum.

    { $group: { _id: "$produit", total: { $sum: "$montant" } } } returns one document per product.

  • Projection: what is it?

    Show the answer

    The second argument of a search: it chooses which fields appear in the returned documents.

    { titre: 1 } keeps the title, but _id is returned too unless you write _id: 0.

  • db.films.find({ annee: "2013" }) returns nothing although Her is in the collection. Which fix is right?

    • Add $exists: true to the filter
    • Replace find with aggregate using the same filter
    • Create an index on annee
    • Compare with the number: { annee: 2013 }
    Show the answer

    Compare with the number: { annee: 2013 }

    MongoDB distinguishes types: the year is stored as a number, and the string "2013" is never equal to it. An index speeds up a search, it does not change what it finds.