查找arrays中位置元素的最大值

我有一个传感器数据的集合,其中每个文档具有以下结构:

[{ _id: 592d9b0e276bd2136caacca0, name: 5 light: [ ... ], temperature: [ ... ], UV: [ ... ], RA: [ ... ] }] 

每个传感器的每个arrays都有100个元素的长度。

例如,我怎样才能find哪个文件名中包含位置为42(温度arrays)的温度值最高的文件?

第一个元素或最后一个元素有很多解决scheme,但我似乎无法find如何解决它的数组的任意位置。

这是我已经有:

 db.sensors.aggregate([ { $unwind: "$name" }, { $sort: { "temperature": -1} }, { $limit: 1} ]); 

但是,正如你所看到的,“{$ sort:{”temperature“:-1}}”的行不起作用。 我真的不明白如何指定我只想sorting温度数组的位置42元素sorting。

如果您正在查找给定位置的值,则可以使用$arrayElemAt来返回提供位置处的值。 对于这个公共数组符号是n-1 ,所以第42位是从索引0开始的41

 db.sensors.aggregate({ { "$addFields": { "pos": { "$arrayElemAt": [ "$temperature", 41 ] } } }}, { "$sort": { "pos": -1 } }, { "$limit": 1 } ]) 

你甚至可以通过使用$exists作为查询参数来加速这个过程,以便只考虑实际上有42个元素的数组,因为其他任何东西都会被忽略:

 db.sensors.aggregate({ { "$match": { "temperature.41": { "$exists": true } } }, { "$addFields": { "pos": { "$arrayElemAt": [ "$temperature", 41 ] } } }}, { "$sort": { "pos": -1 } }, { "$limit": 1 } ]) 

还要注意的是,在没有$addFieldspipe道运算符的早期版本中,您改为使用$project指定所有要返回的字段: