mongodb - mongo中的最小嵌套数组
问题描述
如何使用 $min 函数获取嵌套数组中的最小值(并将其添加到文档中)?
[
{
"_id": "a357e77f-a76a-4bc2-8765-923280663e97",
"customers": [
{
"_id": "97170117-4660-4c6f-b8da-2b34d4d0c9ce",
"orders": [
{
"amount": 0.5
},
{
"amount": 6.400001525878906
}
]
},
{
"_id": "7b9ccf5b-3acb-4ed1-8df4-e3b5afc49cba",
"orders": [
{
"amount": 27.29999542236328
},
{
"amount": 0.29999542236328125
}
]
}
]
},
{
"_id": "58433224-8162-4f0a-8168-bc11b4306b0a",
"customers": [
{
"_id": "8a6055d0-9b94-40be-8f96-8fd9088d24aa",
"orders": [
{
"amount": 19.700000762939453
}
]
},
{
"_id": "a50a57b8-61e7-4727-a15a-4a4137b2f81a",
"orders": [
{
"amount": 43.80000305175781
}
]
}
]
}
]
如何获取 $customers.orders.amount 路径中的最小金额值?
我试过了,但它返回 0。
db.collection.aggregate([
{
$addFields: {
"amount": {
$sum: "$customers.orders.amount"
}
}
}
])
解决方案
您可以为每个客户执行以下操作
db.collection.aggregate([
{//Destruct
"$unwind": "$customers"
},
{//Destruct
"$unwind": "$customers.orders"
},
{//Group by customer id,
$group: {
"_id": "$customers._id",
min: {
$push: {
"$min": "$customers.orders.amount"
}
}
}
}
])
group by null
如果您想在所有客户中找到最小值,则可以使用。
推荐阅读
- android - 我可以从 android 的 system/lib/ 中存在的系统库中的应用程序数据目录 [data/data/com.my.package/files/] 上写入文件吗?
- c# - 如何在 C# 操作中读取 OData URL 参数值?
- sql - 按字符串排序
- reactjs - 运行“npm run lint”时出错
- firebase-realtime-database - Firebase 实时数据库使用自定义规则自动删除空数据库
- java - 与本地环境相比,当我通过简单的 Jdbc 调用在 oracle 中调用过程时,响应时间更高
- qt - 在QML中按下回车键时如何触发按钮单击
- react-native - 项目名称 '@mapbox/react-native-mapbox-gl' 不得包含以下任何字符:[/、\、:、<、>、"、?、*、|]
- ansible - 如何对齐ansible模板中的文本?
- android - 如何使用带有指针箭头的 customLayout 添加弹出菜单并将其锚定到视图