首页 > 解决方案 > MongoDB,获取数组子集的最小值和最大值

问题描述

我试图找到一种方法来从结果中获得最小的orders介于 2019-03-172019-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)
    }
]

}

我尝试使用$minand$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
                            ]
                        }
                    ]
                }
            }
        }
    }
}

])

标签: mongodbaggregation-framework

解决方案


您可以使用$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" },
        }
    }
])

推荐阅读