Sunil P
Sunil P

Reputation: 13

Find max value for array field in mongo

Product collection includes price field. Price field can be a single or multivalued.

Output should be maximum price value.

Input:

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

output:

{ "price": "100" }

Upvotes: 0

Views: 579

Answers (1)

dnickless
dnickless

Reputation: 10918

You should convert your price field to a numerical type but the below works with strings, too:

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 } })

See this thread for how to convert your data: how to convert string to numerical values in mongodb

Upvotes: 1

Related Questions