Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding highest value from sub-arrays in documents

Let say I have the following collection:

{ _id: 1, Array: [
  { K: "A", V: 8 },
  { K: "B", V: 5 },
  { K: "C", V: 13 } ] }

{ _id: 2, Array: [
  { K: "D", V: 12 },
  { K: "E", V: 14 },
  { K: "F", V: 2 } ] }

I would like to run a query that returns the sub-document with the highest "V", so in that case I would get:

{ _id: 1, Array: [ { K: "E", V: 14 } ] }

or simply:

{ K: "E", V: 14 }

The important part is that I want the memory usage on the Mongo server to be O(1) (no matter how many documents I process, the memory usage is constant), and I only want to retrieve that one subdocument with the value I need (I don't want to download more subdocuments than necessary).

My preferred approach would be to use a simple find query, but I'm not sure if that's possible. I suspect this can be also done with the aggregation framework (or map reduce?), but don't see how. I don't want the result stored in a temporary collection, but directly returned to my client (like a normal query).

like image 215
Flavien Avatar asked Feb 15 '13 14:02

Flavien


2 Answers

The following aggratation set returns what you need.

db.letters.aggregate([
    {$project:{"Array.K":1, "Array.V":1}},
    {$unwind:"$Array"},
    {$sort:{"Array.V":-1}},
    {$limit:1}
]);

Returns:

{"_id":2, "Array":{"K":"E","V":14}}

Enjoy! :)

like image 73
Victoria Malaya Avatar answered Oct 20 '22 19:10

Victoria Malaya


As @JohnnyHK said:

db.col.aggregate([
    {$unwind: '$Array'},
    {$group: {_id: '$_id', Array: {K: {$max: '$K'}, V: {$max: '$V'}}}}
])

Something like that.

like image 45
Sammaye Avatar answered Oct 20 '22 19:10

Sammaye