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).
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! :)
As @JohnnyHK said:
db.col.aggregate([
{$unwind: '$Array'},
{$group: {_id: '$_id', Array: {K: {$max: '$K'}, V: {$max: '$V'}}}}
])
Something like that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With