Get latest set of records as of a date in MongoDB

Viewed 35

I'm using a time-series collection in MongoDb and want to query for the latest set of records as of (on or before) a date. E.g. Querying for 2022-01-15 would return all the records in Set: abc
Querying for 2022-01-31 would return all records in Set: xyz.

ID: 1, Set: abc, Value: 100, AsAtDate: 2022-01-01
ID: 2, Set: abc, Value: 200, AsAtDate: 2022-01-01
ID: 3, Set: xyz, Value: 300, AsAtDate: 2022-01-31
ID: 4, Set: xyz, Value: 400, AsAtDate: 2022-01-31
1 Answers

collection.find().sort({AsAtDate: -1}, function(err, cursor){...});

This will sort your collection in descending order based on the date

Related