Reputation: 5469
In C#
how can I get last N
inserted documents from the collection in mongo
?
Upvotes: 2
Views: 7354
Reputation: 5469
I made solution
SortByBuilder sbb = new SortByBuilder();
sbb.Descending("_id");
var allDocs = collection.FindAllAs<BsonDocument>().SetSortOrder(sbb).SetLimit(N);
Upvotes: 8
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