MongoDB,获取数组子集的最小和最大值

时间:2019-03-21 22:30:06

标签: mongodb aggregation-framework

我正试图找到一种方法,以使两者之间的最低数量为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)
    }
]

}

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

])

1 个答案:

答案 0 :(得分:1)

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