vesii
vesii

Reputation: 3128

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?

Upvotes: 1

Views: 42

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

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

Upvotes: 1

Related Questions