Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

mongodb - 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...