0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.