0

I have a document that looks like this.

{
  city: "Manhattan",
  State: "NY",
  eth:[
    {02: 40},
    {15:50},
    {04:10}
  ]

}

What I wanna do is find the object within the eth array with the max value. I have tried doing this.

project:{
  {'eth':{$reduce:{
                        input:"$eth",
                        initialValue:1,
                        in:{$max:["$$value","$$this"]}
                    }}}
            ,{
            $project:{"eth":{$objectToArray:"$eth"}},
        }
}

which results into [{k: 15, v:60}].

How do I get the value of k as my eth. I tried doing another project where I tried to get "$eth[0].k" but it results as undefined.

I want the output to look like :

{
  city: "Manhattan",
  state:"NY",
  eth: 15
}

1 Answer 1

1

You can simply use $max to get the max value

db.collection.aggregate([
  { "$project": {
    "max": {
      "$objectToArray": {
        "$max": "$eth"
      }
    }
  }},
  { "$project": {
    "eth": {
      "$arrayElemAt": ["$max.k", 0]
    }
  }}
])
Sign up to request clarification or add additional context in comments.

2 Comments

That works for max. Is there a way I could just get the key for the max value since it has no name. I need to group based on the key right after this project stage
Thank you, I did something similar but I just did eth.k to access in group statement.

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.