从文档中的子数组中查找最高值 [英] Finding highest value from sub-arrays in documents
问题描述
假设我有以下收藏:
{ _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 } ] }
我想运行一个返回具有最高V"的子文档的查询,所以在这种情况下我会得到:
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 } ] }
或者简单地说:
{ K: "E", V: 14 }
重要的部分是我希望 Mongo 服务器上的内存使用量为 O(1)(无论我处理多少个文档,内存使用量都是恒定的),并且我只想用我需要的值(我不想下载不必要的子文档).
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).
我的首选方法是使用简单的查找查询,但我不确定这是否可行.我怀疑这也可以通过聚合框架(或 map reduce?)来完成,但不知道如何.我不希望将结果存储在临时集合中,而是直接返回给我的客户端(就像普通查询一样).
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}
]);
返回:
{"_id":2, "Array":{"K":"E","V":14}}
享受吧!:)
这篇关于从文档中的子数组中查找最高值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!