mongodb - 如何计算 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"
}
]
}
]
}
我有订单集合,其中文档采用这种格式。我想获得具有可退货标志的产品总数。例如:对于上述订单,计数应为2。我对 MongoDB 很陌生,想知道如何编写查询来找出答案,我尝试了几件事但没有帮助:这是我尝试过但没有奏效的方法:
db.orders.aggregate([
{ "$unwind": "$bags" },
{ "$unwind": "$bags.products" },
{ "$unwind": "$bags.products.returnable" },
{ "$group": {
"_id": "$bags.products.returnable",
"count": { "$sum": 1 }
}}
])
解决方案
对于内部数组,您可以使用$filter检查returnable
标志和$size来获取此类项目的数量。对于外部,您可以利用$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 ]
}
}
}
]
}
}
}
}
}
}
])
推荐阅读
- javascript - 在 angular2 中创建图表以显示给定数据的中值
- c# - 运行子表单时防止初始表单“刷新”
- android - 从 Android Studio 中的 URL 解析 Json 文件数据
- python-3.x - 为什么不能从 cartopy-geopandas 图中设置为“假”特定轴刻度标签(例如:xlabels_top、ylabels_right)?
- swift - textField 允许所有字符,尽管 ShouldChangeCharactersIn 函数
- javascript - 如何使用此处的 api 添加地理坐标图以形成
- java - Java 移动文件
- python-3.6 - python - 找到一个主题 - 输入:一个 .txt 文件,包含 10 个序列和 10 个主题
- javascript - React-native get 方法返回值
- terminal - Ranger 不会显示图像预览