首页 > 解决方案 > 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?

标签: mongodbmongodb-queryaggregation-framework

解决方案


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} ]

推荐阅读