【发布时间】:2021-05-12 13:11:43
【问题描述】:
{
"orderNo": "123",
"bags": [{
"type": "small",
"products": [{
"id": "1",
"name": "ABC",
"returnable": true
}, {
"id": "2",
"name": "XYZ"
}
]
},{
"type": "big",
"products": [{
"id": "3",
"name": "PQR",
"returnable": true
}, {
"id": "4",
"name": "UVW"
}
]
}
]
}
我有订单集合,其中文档采用这种格式。我想获得具有 returnable 标志的 products 的总数。例如:对于上述顺序,计数应为 2。我对 MongoDB 很陌生,想知道如何编写查询来找出答案,我尝试了几件事,但没有帮助: 这是我尝试过但没有奏效的方法:
db.orders.aggregate([
{ "$unwind": "$bags" },
{ "$unwind": "$bags.products" },
{ "$unwind": "$bags.products.returnable" },
{ "$group": {
"_id": "$bags.products.returnable",
"count": { "$sum": 1 }
}}
])
【问题讨论】:
-
您的预期结果是什么?
标签: mongodb mongodb-query nosql aggregation-framework