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).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…