mongodb - Get maximum value for a field, but only with respect to other documents with the same value in another field
问题描述
I have mongodb documents like this:
{'device':'A','value':12}
{'device':'A','value':13}
{'device':'A','value':14}
{'device':'B','value':4}
{'device':'B','value':5}
I would like to find
{'device':'A','value':14}
{'device':'B','value':5}
i.e. for each device
(here A
and B
) the documents with the highest value
.
What I am doing so far is to find all the distinct devices in one query and then get all the documents for each device individually sorted descending with a limit of 1. But this needs lots of queries.
Is there a way to do this in one query?
解决方案
推荐阅读
- c++ - 以内存为重点,在数组中查找 k 个最小/最大元素
- python - Spark:IllegalArgumentException:'不支持的类文件主要版本 55'
- php - Ajax 重载框架只工作一次
- flutter - 聚焦时将光标定位在 TextField 的末尾?
- node.js - ExpressJs 与 NodeJs 版本的兼容性
- javascript - 将鼠标悬停在破折号中的点上时突出显示日志
- ruby-on-rails - 我在哪里可以找到 Rails 作业的域设置?
- airflow - Airflow 基本身份验证隐藏了 Admin -menu 选项
- java - 在android上向谷歌地图添加坐标
- datagrip - Datagrip:带参数在oracle中执行sql语句