0
0
MongoDBquery~5 mins

$facet for multiple pipelines in MongoDB

Choose your learning style9 modes available
Introduction

The $facet stage lets you run many different queries on the same data at once. It helps you get multiple results in one go.

You want to get counts and details from the same data without running separate queries.
You need to group data in different ways and see all results together.
You want to save time by running multiple analyses on your data in one step.
Syntax
MongoDB
db.collection.aggregate([
  {
    $facet: {
      pipeline1Name: [ /* stages for first pipeline */ ],
      pipeline2Name: [ /* stages for second pipeline */ ]
    }
  }
])

Each pipeline inside $facet runs independently on the same input data.

The output is one document with fields named after each pipeline, each holding an array of results.

Examples
This example calculates total and average sales in one query.
MongoDB
db.sales.aggregate([
  {
    $facet: {
      totalSales: [ { $group: { _id: null, total: { $sum: "$amount" } } } ],
      averageSales: [ { $group: { _id: null, avg: { $avg: "$amount" } } } ]
    }
  }
])
This example splits products into cheap and expensive lists.
MongoDB
db.products.aggregate([
  {
    $facet: {
      cheapProducts: [ { $match: { price: { $lt: 20 } } } ],
      expensiveProducts: [ { $match: { price: { $gte: 20 } } } ]
    }
  }
])
Sample Program

This query gets three results at once: total number of orders, count of orders by status, and the 3 most recent orders.

MongoDB
db.orders.aggregate([
  {
    $facet: {
      totalOrders: [ { $count: "count" } ],
      ordersByStatus: [ { $group: { _id: "$status", count: { $sum: 1 } } } ],
      recentOrders: [ { $sort: { orderDate: -1 } }, { $limit: 3 } ]
    }
  }
])
OutputSuccess
Important Notes

Each pipeline inside $facet can have multiple stages like $match, $group, $sort, etc.

The output document always has one field per pipeline, each containing an array of results.

Use $facet to avoid running multiple separate queries when you want different views of the same data.

Summary

$facet runs many pipelines on the same data at once.

It returns one document with results from each pipeline as separate arrays.

Great for getting multiple summaries or lists in a single query.