Lecture: Lecture 22 - Introduction to MongoDB
Related: MongoDB BSON Documents Collections and CRUD Operations · MongoDB Polyglot Persistence Hadoop and Apache Spark · Query Optimization Pipeline and Relational Algebra

MongoDB Compass GUI (Slides 24–32)

MongoDB Compass is the official cross-platform GUI (Linux, Mac, Windows) for visually exploring and analyzing MongoDB collections without writing raw shell scripts (Slide 25):

  • Connect (Slide 26): Connects to local or remote MongoDB instances (default port 27017, optional authentication database and replica-set/read-preference settings).
  • Browse documents (Slide 27): Inspects collection documents in either list (JSON-like expandable tree) or table format.
  • Schema & Geospatial analysis (Slides 28–29): Analyzes field types/distributions across documents and provides native geospatial coordinate mapping—you can drag on the map to visually build $geoWithin / $centerSphere queries (e.g., { interior: 'GOOD', loc: { $geoWithin: { $centerSphere: [...] } } }).
  • Query builder (Slide 30): Constructs queries step by step with autocomplete enabled by default across FILTER, PROJECT, SORT, COLLATION, SKIP, and LIMIT.
  • Explain Plan (Slide 31): Visualizes query execution trees and performance summaries (Documents Returned, Index Keys Examined, Documents Examined, Sorted in Memory), surfacing warnings such as “No index available for this query” so you know when to add an index.
  • Validation (Slide 32): Defines $jsonSchema constraints (e.g., required fields ['exterior', 'interior', 'vendor', 'fuel'], bsonType: "string" / "int", strict/error levels) and previews matching vs. failing documents to catch inconsistent records.

Aggregation pipelines (Slides 33–36)

Instead of a single monolithic SELECT ... GROUP BY ... HAVING statement, MongoDB processes documents through an ordered pipeline of stages ($match, $group, $count, $limit, $geoNear, $graphLookup, etc.; Slide 33). Each stage transforms the incoming documents and passes its output documents to the next stage.

Mapping $group to SQL GROUP BY (Slides 34–35)

In a $group stage:

  • _id corresponds to the GROUP BY parameter in SQL (e.g., _id: "$vendor" creates one output document per distinct vendor).
  • Additional fields define the aggregated attributes computed per group, such as total: { $sum: 1 } (counts documents by adding 1 per document, equivalent to COUNT(*)) and avg_fuel: { $avg: "$fuel" } (AVG(fuel)).

Worked source pipeline on dbdmg.Parkings (Slide 36)

Goal: Compute the total bookings/parkings and average fuel level per car-sharing vendor, then keep only vendors with avg_fuel > 63 and total > 35000.

[
  // Stage 1: Group by vendor (SQL GROUP BY vendor)
  {
    $group: {
      _id: "$vendor",
      total: { $sum: 1 },
      avg_fuel: { $avg: "$fuel" }
    }
  },
  // Stage 2: Filter on fields CREATED in Stage 1 (SQL HAVING!)
  {
    $match: {
      avg_fuel: { $gt: 63 },
      total: { $gt: 35000 }
    }
  }
]
  • After Stage 1 ($group): { _id: "car2go", total: 48423, avg_fuel: 64.8828... } and { _id: "enjoy", total: 30134, avg_fuel: 61.0338... }.
  • After Stage 2 ($match): Only { _id: "car2go", total: 48423, avg_fuel: 64.8828... } survives (enjoy fails both conditions).

Stage ordering: $match before vs. after $group

A common question is whether $group comes before $match in Slide 36 as an optimization. In fact, stage order is dictated first by correctness (matching SQL WHERE vs. HAVING), and only then by optimization:

PatternSQL EquivalentWhy this order is required
$group → $match (Slide 36)GROUP BY ... HAVING ...Correctness: avg_fuel and total do not exist yet on the raw documents—$group must compute them before $match can filter on them.
$match → $groupWHERE ... GROUP BY ...Correctness + Optimization: When filtering on a raw document field (e.g., fuel > 20), $match must run before $group so excluded cars do not distort COUNT(*)/AVG(fuel) (and individual fuel fields disappear after grouping). It also speeds up execution by shrinking the documents entering $group (analogous to selection pushdown in Query Optimization Pipeline and Relational Algebra).

Added study example: translating WHERE + GROUP BY (outside the PDF)

(Added example from our study session, outside the source PDF): Translate the following SQL query on Parkings into a 2-stage MongoDB pipeline:

SELECT city, COUNT(*) AS n_cars, AVG(fuel) AS mean_fuel
FROM Parkings
WHERE fuel > 20
GROUP BY city

Because fuel > 20 tests a raw field on each document (WHERE), $match comes first, followed by $group:

[
  { $match: { fuel: { $gt: 20 } } },
  {
    $group: {
      _id: "$city",
      n_cars: { $sum: 1 },
      mean_fuel: { $avg: "$fuel" }
    }
  }
]

Common confusions

  • Thinking Slide 36 puts $group before $match for speed: Putting $group first on raw-field filters would actually be slower and wrong; Slide 36 puts $group first only because avg_fuel and total are newly created aggregate fields (HAVING).
  • Forgetting the $ prefix on field references inside $group: In _id: "$vendor" and { $avg: "$fuel" }, the $ tells MongoDB to read the value of that field from each document rather than grouping by the literal string "vendor".
  • Ignoring Explain Plan (Index Keys Examined: 0): Even with $geoWithin or $match filters, Compass shows Documents Examined: 100 (full collection scan) until an appropriate index is created.

Retrieval questions with answers

1. In a MongoDB $group stage, what does _id represent, and what does { $sum: 1 } compute?
_id specifies the grouping key—equivalent to the GROUP BY expression in SQL. { $sum: 1 } adds 1 for every document in each group, which is equivalent to COUNT(*).

2. Why does Slide 36 place $match after $group, whereas a query filtering WHERE fuel > 20 must place $match before $group?
In Slide 36, $match filters on avg_fuel and total, which are computed by $group (SQL HAVING), so $group must run first for correctness. For WHERE fuel > 20, fuel is a raw document field that disappears after grouping; putting $match first ensures excluded documents are neither counted nor averaged and reduces the data entering $group.

3. In MongoDB Compass’s Explain Plan tab, what does seeing Index Keys Examined: 0 alongside “No index available for this query” tell you?
MongoDB could not use any index and had to scan every document in the collection (plus sort in memory if sorting was requested), indicating that creating an index on the filtered/sorted fields would speed up the query.