We Reduced 3 Queries to 1 Using This MongoDB Trick

Darshit AnjariaDarshit Anjaria
4 min read

Hey devs! 👋

Need multiple analytics in a single MongoDB query? The $facet stage is your go-to! 🚀

It lets you run multiple pipelines in parallel—perfect for dashboards, reports, and multi-metric APIs. Let’s see how it works! 🔍


Ever wished you could run multiple queries on the same dataset simultaneously—without sending separate requests or looping through collections? That's exactly what MongoDB’s $facet stage offers. It’s a powerful yet often underused part of the aggregation framework that can drastically simplify complex data transformations.

Let’s dive into what $facet is, how it works, and where it shines the brightest—with a real-world use case and a simple pipeline to help you master it.


What is the $facet Stage in MongoDB? 🔍

The $facet stage in MongoDB's Aggregation Pipeline allows you to perform multiple independent aggregations in parallel on the same dataset. Think of it like a split-view lens—where you take one stream of documents and observe it from multiple angles at once.

Each “facet” is its own mini-pipeline, and all the results are bundled together into a single document output.

Syntax Overview ✅:

{
  $facet: {
    facet1: [ /* pipeline stages */ ],
    facet2: [ /* pipeline stages */ ],
    ...
  }
}

Each key inside $facet is the name of a sub-pipeline, and the value is an array of aggregation stages that run independently from the others.


Real-World Analogy 🌍

Imagine you're running an e-commerce store. You want to show the following on your dashboard:

  • Top 5 best-selling products

  • Latest 5 customer reviews

  • Count of total orders placed

Traditionally, you'd have to run three different queries. But with $facet, you can do all of that in a single aggregation—in one database round trip!


When & Why to Use $facet 🛠️

Ideal Use Cases ✅:

  • Dashboards that need multiple aggregations at once

  • APIs that return combined stats and subsets

  • Advanced filtering + pagination in a single request

  • Any time you want to avoid multiple DB round trips

Benefits 🚀:

  • Performance boost by minimizing database queries

  • Cleaner code by consolidating logic

  • Easy to return structured output for front-end apps


Real-World Example: Product Insights Dashboard 📦

Let’s walk through a sample use case.

Scenario: You're building an API endpoint /products/overview that needs to return:

  • The top 3 products by sales

  • The latest 2 customer reviews

  • The total number of products in the store

Sample Data Collection: products

{
  "_id": ObjectId("..."),
  "name": "Wireless Earbuds",
  "sales": 1200,
  "reviews": [
    { "rating": 5, "comment": "Awesome!", "date": ISODate("2024-12-10") },
    { "rating": 4, "comment": "Pretty good", "date": ISODate("2024-11-15") }
  ],
  "createdAt": ISODate("2023-05-20")
}

Aggregation Pipeline Using $facet 💡:

db.products.aggregate([
  {
    $facet: {
      topSelling: [
        { $sort: { sales: -1 } },
        { $limit: 3 },
        { $project: { name: 1, sales: 1, _id: 0 } },
      ],
      latestReviews: [
        { $unwind: "$reviews" },
        { $sort: { "reviews.date": -1 } },
        { $limit: 2 },
        {
          $project: {
            review: "$reviews.comment",
            rating: "$reviews.rating",
            _id: 0,
          },
        },
      ],
      totalCount: [{ $count: "totalProducts" }],
    },
  },
]);

Sample Output 🧾:

{
  "topSelling": [
    { "name": "Wireless Earbuds", "sales": 1200 },
    { "name": "Smart Watch", "sales": 950 },
    { "name": "Portable Speaker", "sales": 870 }
  ],
  "latestReviews": [
    { "review": "Awesome!", "rating": 5 },
    { "review": "Pretty good", "rating": 4 }
  ],
  "totalCount": [{ "totalProducts": 50 }]
}

Final Thoughts 🧠

The $facet stage is like the Swiss Army knife of MongoDB aggregation. When used smartly, it can greatly optimize how you retrieve and transform data—especially in dashboard or analytics-heavy applications.

Whether you’re building a product overview API, a metrics panel, or a personalized feed, $facet helps you do more with less.


Thank You!

Thank you for reading!
I hope you enjoyed this post. If you did, please share it with your network and stay tuned for more insights on software development. I'd love to connect with you on LinkedIn or have you follow my journey on HashNode for regular updates.

Happy Coding!
Darshit Anjaria

2
Subscribe to my newsletter

Read articles from Darshit Anjaria directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Darshit Anjaria
Darshit Anjaria

I’m a problem solver at heart, driven by the idea of building solutions that genuinely make a difference in people’s everyday lives. I’m always curious, always learning, and always looking for ways to improve the world around me through thoughtful, impactful work. Beyond building, I love giving back to the community — whether it’s by sharing what I’ve learned through blogs, tutorials, or helpful insights. My goal is simple: to make technology a little more accessible and useful for everyone. Let’s learn, build, and grow together.