mongodb - MongoDB,获取数组子集的最小值和最大值
问题描述
我试图找到一种方法来从结果中获得最小的orders
介于
2019-03-17
和2019-03-19
排除之间的数量2019-03-15
..
{
"_id" : ObjectId("5c8ffdadde62bf097d54ec47"),
"productId" : "32886845998",
"orders" : [
{
"date" : ISODate("2019-03-15T00:00:00.000+0000"),
"orders" : NumberInt(9)
},
{
"date" : ISODate("2019-03-17T00:00:00.000+0000"),
"orders" : NumberInt(21)
},
{
"date" : ISODate("2019-03-18T00:00:00.000+0000"),
"orders" : NumberInt(20)
},
{
"date" : ISODate("2019-03-19T00:00:00.000+0000"),
"orders" : NumberInt(30)
}
]
}
我尝试使用$min
and$max
运算符,但这没有帮助,因为它遍历整个数组以找到最大值和最小值
db.products.aggregate([
{
$project: {
maximum: {
$reduce: {
input: "$orders",
initialValue: 0,
in: {
$max: [
"$$value",
{
$cond: [
{ $gte: [ "$$this.date", ISODate("2019-03-17T00:00:00.000+0000") ] },
"$$this.orders",
0
]
}
]
}
}
}
}
}
])
解决方案
您可以使用$filter来应用过滤orders.date
,然后您可以在过滤集上应用$min和$max :
db.col.aggregate([
{
$project: {
filteredOrders: {
$filter: {
input: "$orders",
cond: {
$and: [
{ $gte: [ "$$this.date", ISODate("2019-03-17T00:00:00.000+0000") ] },
{ $lte: [ "$$this.date", ISODate("2019-03-19T00:00:00.000+0000") ] },
]
}
}
}
}
},
{
$project: {
min: { $min: "$filteredOrders.orders" },
max: { $max: "$filteredOrders.orders" },
}
}
])
推荐阅读
- javascript - 尝试遍历 django 模板中的嵌套字典
- python - 学习python中的类和对象
- c# - 如何访问 SkiaSharp 调色板进行量化?
- javascript - changing element in ngOnInit not working when changing route, but is able to access element
- r - 当分配规则存储在另一个tibble中时,如何用新值替换tibble中的数据?
- javascript - 如何在本机反应中发出 POST 请求
- docker - WebStorm Docker 配置 paramiko.ssh_exception.NoValidConnectionsError
- xml - XPath 可以按中间节点对选定节点列表进行分组吗?
- r - 使用 R 将列中的 NA 值替换为数字列表
- android - Jetpack Compose 中 Box 内的组件中的 `fillMaxSize()` 和 `matchParentSize()` 有什么区别?