Saint
Saint

Reputation: 5469

How to get last N documents from collection in mongo?

In C# how can I get last N inserted documents from the collection in mongo?

Upvotes: 2

Views: 7354

Answers (2)

Saint
Saint

Reputation: 5469

I made solution

SortByBuilder sbb = new SortByBuilder();
sbb.Descending("_id");
var allDocs = collection.FindAllAs<BsonDocument>().SetSortOrder(sbb).SetLimit(N);

Upvotes: 8

user2665694
user2665694

Reputation:

The general pattern is using

docs = collection.find().sort({'_id' : -1}.limit(N)

By sorting on _id you will take into account that the standard object id is only increasing over time (unless implemented otherwise). Otherwise you need to sort on some timestamp field that you add/maintain within your code and application.

Upvotes: 1

Related Questions