MongoDB Aggregation Pipelines for Sub-Second Catalog Pages

MongoDB Aggregation Pipelines for Sub-Second Catalog Pages

Indexes, $lookup tuning and pre-computed facets that took a B2B energy marketplace's catalog from slow to instant.

Surge is a B2B renewable energy marketplace. Its catalog pages combine products, vendors, pricing tiers and filters, which is exactly where naive queries become slow. Here is the approach that got those pages to sub-second load times.

Filter early, project early

The single biggest win in any pipeline is putting $match first and making sure it can use an index. Follow it with $project to drop fields you will never send to the client, so every later stage handles smaller documents.

db.products.aggregate([
  { $match: { status: "active", category: cat } },
  { $project: { name: 1, price: 1, vendorId: 1, rating: 1 } },
  { $sort: { rating: -1 } },
  { $limit: 24 },
]);

Use $facet for filters and results in one round trip

Catalog pages need both the results and the filter counts. $facet runs several sub-pipelines over the same matched set, so you get the page of products and the counts per brand or price band in a single query.

Be careful with $lookup

  • Run $lookup after $limit when you only need joined data for the visible page.
  • Use the pipeline form of $lookup to project only the fields you need from the joined collection.
  • Index the foreign field, otherwise every lookup scans.

Compound indexes that match the query

Follow the equality, sort, range rule when designing compound indexes. An index on { status: 1, category: 1, rating: -1 } supports the match and the sort above without an in-memory sort.

Measure with explain()

Run explain("executionStats") on every hot pipeline. If totalDocsExamined is far bigger than nReturned, the index is not doing its job. Fixing that one ratio usually matters more than any clever stage.

More on this topic

Photography
3D Models
Development
Illustrations
Fashion
Digital Art
Packaging
Motion
Illustrations
Video Production
Photography
3D Models
Development
Illustrations
Fashion