如何计算 mongoDB 中的嵌入式数组对象元素
How to count embedded array object elements in mongoDB
{
"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 }
}}
])
对于内部数组,您可以使用 $filter to check returnable
flag and $size to get number of such items. For the outer one you can take advantage of $reduce 对内部数组的值求和:
db.collection.aggregate([
{
$project: {
totalReturnable: {
$reduce: {
input: "$bags",
initialValue: 0,
in: {
$add: [
"$$value",
{
$size: {
$filter: {
input: "$$this.products",
as: "prod",
cond: {
$eq: [ "$$prod.returnable", true ]
}
}
}
]
}
}
}
}
}
}
])
{
"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 }
}}
])
对于内部数组,您可以使用 $filter to check returnable
flag and $size to get number of such items. For the outer one you can take advantage of $reduce 对内部数组的值求和:
db.collection.aggregate([
{
$project: {
totalReturnable: {
$reduce: {
input: "$bags",
initialValue: 0,
in: {
$add: [
"$$value",
{
$size: {
$filter: {
input: "$$this.products",
as: "prod",
cond: {
$eq: [ "$$prod.returnable", true ]
}
}
}
]
}
}
}
}
}
}
])