4. Filtering Documents with $match

$match selects documents using familiar MongoDB query predicates, including equality, comparison, logical, array, and existence conditions. Multiple fields in one match object imply AND.

Place selective source filters early when possible. An initial $match may use an appropriate index, but index use depends on query shape, selectivity, available indexes, and the execution plan.

For date ranges, a half-open interval is often convenient: use $gte for the start and $lt for the end. This avoids overlap between adjacent reporting periods.

Code Example
db.orders.aggregate([
  {
    $match: {
      status: "delivered",
      shippingFee: { $gte: 50 },
      createdAt: {
        $gte: ISODate("2026-10-01T00:00:00Z"),
        $lt: ISODate("2026-10-06T00:00:00Z")
      }
    }
  },
  { $project: { customerId: 1, status: 1, createdAt: 1, shippingFee: 1 } }
]);
Key Takeaways
  • $match uses query predicates.
  • Multiple fields imply AND.
  • Early filters can reduce downstream work.
  • Use consistent date boundaries.
Knowledge Check

Where should a selective source filter generally appear if it preserves the required meaning?