$facet
$facet 是 MongoDB 中的一个聚合操作符,它允许在单个聚合阶段中并行执行多个子聚合操作。每个 $facet 阶段都可以包含多个子阶段,这些子阶段可以独立地对输入文档集进行处理。下面是一个使用案例,包括插入和测试数据。
首先,让我们考虑一个假设的场景:假设我们有一个名为 “orders” 的集合,其中存储了客户订单的信息。每个订单文档包含了客户 ID、订单日期、订单总额等字段。我们希望通过使用 $facet 聚合操作符,同时获取两种不同的汇总数据:一种是按月份汇总订单总额,另一种是按客户 ID 汇总订单数量。
1,插入测试数据
db.orders.insertMany([
{ customerId: "customer1", orderDate: ISODate("2023-01-15"), totalAmount: 100 },
{ customerId: "customer2", orderDate: ISODate("2023-01-20"), totalAmount: 150 },
{ customerId: "customer1", orderDate: ISODate("2023-02-10"), totalAmount: 200 },
{ customerId: "customer3", orderDate: ISODate("2023-02-28"), totalAmount: 300 },
{ customerId: "customer",orderDate: ISODate("2023-03-05"), totalAmount: 120 }
])
2,使用 $facet 进行聚合查询
db.orders.aggregate([
{
$match: { customerId: { $ne: "customer" } } // match排除筛选
},
{
$facet: {
"monthlySummary": [
{
$group: {
_id: { $month: "$orderDate" },
totalAmount: { $sum: "$totalAmount" }
}
},
{
$sort: { _id: 1 }
}
],
"customerSummary": [
{
$group: {
_id: "$customerId",
totalOrders: { $sum: 1 }
}
}
]
}
}
])
运行结果: