我有以下集合,我想使用 MongoDB 聚合来实现以下输出。
[
{
"order_line_item_id": 1
"order_id": 100,
"products": [
{"name": "Shoe","hasDefect": "YES",},
{"name": "Pant","hasDefect": "NO",},
{"name": "Shirt","hasDefect": "NOT_SURE",},
],
},
{
"order_line_item_id": 2
"order_id": 100,
"products": [
{"name": "Shoe","hasDefect": "YES",},
{"name": "Pant","hasDefect": "YES",},
{"name": "Shirt","hasDefect": "YES",},
],
},
{
"order_line_item_id": 3
"order_id": 101,
"products": [
{"name": "Shoe","hasDefect": "YES",},
{"name": "Pant","hasDefect": "NO",},
{"name": "Shirt","hasDefect": "NOT_SURE",},
],
},
]
我想按订单对它们进行分组,并根据条件在订单级别汇总“hasDefect”:
对于上述集合,对于订单 id:100,预期输出类似于:
[
{
"order_id": 100,
{
"products": [
{"name": "Shoe","hasDefect": "YES",},
{"name": "Pant","hasDefect": "NO",},
{"name": "Shirt","hasDefect": "NOT_SURE",},
}
}
]
$unwind
- 将 products
数组解构为多个文档。
$group
- 按 order_id
和 products_name
分组。添加值为 hasDefects
的 products.hasDefect
数组。
$set
- 设置 hasDefect
字段。按条件对状态进行分类 ($switch
)。
$group
- 按 _id.order_id
分组。添加 products
数组。
db.collection.aggregate([
{
$unwind: "$products"
},
{
$group: {
_id: {
order_id: "$order_id",
productName: "$products.name"
},
hasDefects: {
$push: "$products.hasDefect"
}
}
},
{
$set: {
hasDefect: {
$switch: {
branches: [
{
case: {
$allElementsTrue: {
$map: {
input: "$hasDefects",
as: "d",
in: {
$eq: [
"$$d",
"YES"
]
}
}
}
},
then: "YES"
},
{
case: {
$in: [
"NO",
"$hasDefects"
]
},
then: "NO"
},
{
case: {
$in: [
"NOT_SURE",
"$hasDefects"
]
},
then: "NOT_SURE"
}
],
default: "<DEFAULT>"
}
}
}
},
{
$group: {
_id: "$_id.order_id",
products: {
$push: {
name: "$_id.productName",
hasDefect: "$hasDefect"
}
}
}
}
])