The $facet stage lets you run many different queries on the same data at once. It helps you get multiple results in one go.
$facet for multiple pipelines in 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.
db.sales.aggregate([
{
$facet: {
totalSales: [ { $group: { _id: null, total: { $sum: "$amount" } } } ],
averageSales: [ { $group: { _id: null, avg: { $avg: "$amount" } } } ]
}
}
])db.products.aggregate([
{
$facet: {
cheapProducts: [ { $match: { price: { $lt: 20 } } } ],
expensiveProducts: [ { $match: { price: { $gte: 20 } } } ]
}
}
])This query gets three results at once: total number of orders, count of orders by status, and the 3 most recent orders.
db.orders.aggregate([
{
$facet: {
totalOrders: [ { $count: "count" } ],
ordersByStatus: [ { $group: { _id: "$status", count: { $sum: 1 } } } ],
recentOrders: [ { $sort: { orderDate: -1 } }, { $limit: 3 } ]
}
}
])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.
$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.