在mongo中查找数组字段的最大值

时间:2018-06-19 14:17:14

标签: mongodb mongodb-query

产品集合包括价格字段。价格字段可以是单值或多值。

输出应为最大价格值。

输入:

{
    "_id": ObjectId("5b239304c70f3826b2862f83"),
    "price": ["09.8", "90.86"]
 } {
    "_id": ObjectId("5b239304c70f3826b2862f84"),
    "price": ["100"]
 } {
    "_id": ObjectId("5b239304c70f3826b2862f85"),
    "price": "95"
 }

输出:

{ "price": "100" }

1 个答案:

答案 0 :(得分:0)

您应该将price字段转换为数字类型,但以下内容也适用于字符串:

db.collection.aggregate([{
    $group: {
        _id: null, // group all documents into the same bucket
        price: { // create a new field "price"
            $max: { // which will be the maximum of
                $cond: [
                    { $eq: [ { $type: "$price" }, "array" ] }, // if the "price" field is an array
                    { $reduce: { input: "$price", initialValue: 0, in: { $max: [ "$$this", "$$value" ] } } }, // the maximum value inside the value
                    "$price" // otherwise just the value of the "price" field
                ]
            }
        }
    }
 }], { collation: { locale: "en_US", "numericOrdering": true } })

有关如何转换数据的信息,请参见以下线程:how to convert string to numerical values in mongodb