mongodb - How to get only the latest doc with aggregation in Mongodb?
问题描述
I'm using the MongoDB aggregation to fetch all reports with the following steps:
[ { '$match': { name: 'test' } },
{ '$sort': { timestamp: -1 } } ]
I want to add a step that will get the last added report by timestamp. So I will get only one latest report. Which step should I add?
解决方案
As you're sorting on timestamp
in descending order so the first document after sort stage will be the latest, So you need to use $limit to get one document out.
[ { '$match': { name: 'test' } },
{ '$sort': { timestamp: -1 } },
{'$limit': 1} ]
推荐阅读
- visual-studio - ASPNETCOMPILER (0,0): ASPRUNTIME 错误: 对象引用未设置为对象的实例
- javascript - 从数组中获取最后一个 Api 数据
- c# - 关键字查询以从 ContentType 列中获取值
- mysql - 返回多条记录,但每个类似条件应限制 1 条记录
- python - 在python中读取类似结构的pdf表格(不是精确的表格)并将其提取为任何文件格式
- java - Wildfly 18 JMS 执行导致“远程连接突然关闭”
- python - python selenium定位元素问题
- c++ - 如何在 C++ 中使用移动语义进行运算符重载?(优雅地)
- java - 如何使用 Firebase 数据库中的数据在 RecyclerView 上实现加载更多分页(无限滚动)
- c++ - C++ 表示回文