在数组中查找max元素 [英] Find max element inside an array

查看:77
本文介绍了在数组中查找max元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

REF:来自字段值最大为max的数组中的MongoDB文档

从文档中的子数组中找到最高价值的答案 MongoDB在文档数组中按最大值查找建议使用sort + limit(1),但这确实很慢.当然可以使用$ max运算符.

Answers in Finding highest value from sub-arrays in documents and MongoDB find by max value in array of documents suggest to use sort + limit(1), however this is really slow. Surely there is a way to use the $max operator.

假设某人通过汇总匹配获得了这样的文档:

Suppose one gets a document like this in an aggregate match:

{
  _id: "notImportant",
  array: [
    {
      name: "Peter",
      age: 17
    },
    {
      name: "Carl",
      age: 21
    },
    {
      name: "Ben",
      age: 15
    }
  ]
}

您想找到年龄最高的(整个,而不仅仅是一个值)文档. 您如何使用$ max运算符来做到这一点?

And you want to find the (entire, not just the one value) document where age is highest. How do you do that with the $max operator?

我尝试过

unwind {"$array"}
project {"_id": 0, "name": "$array.name", "age": "$array.age"}

所以我得到

{
  _id: null,
  name: "Peter",
  age: 17
}
{
  _id: null,
  name: "Carl",
  age: 21
}
{
  _id: null,
  name: "Ben",
  age: 15
}

然后我尝试匹配年龄:

age: {$eq: {$max: "$age"}}

,但是没有任何结果.

换句话说,我需要得到的是名称和所有其他属于数组中最早的人的字段.有成千上万的人,具有许多属性,最重要的是,它全部在树莓派上运行.我需要在几十个这样的阵列上执行此操作.因此,通过排序,总共大约需要40秒.所以我真的不想使用排序.

In other words what I need to get is the name and all other fields that belong to the oldest person in the array. And there are many thousands of persons, with lots of attributes, and on top of it all it runs on a raspberry pi. And I need to do this operation on a few dozen of such arrays. So with the sorting this takes about 40 seconds all in all. So I would really like to not use sort.

推荐答案

您可以使用$reduce

db.t63.aggregate([
    {$addFields : {array : {$reduce : {
        input : "$array", 
        initialValue : {age : 0}, 
        in : {$cond: [{$gte : ["$$this.age", "$$value.age"]},"$$this", "$$value"]}}
    }}}
])

输出

{ "_id" : "notImportant", "array" : { "name" : "Carl", "age" : 21 } }

这篇关于在数组中查找max元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆