Get the latest document from collection

Do I need to do the sorting explicitly or can I safely remove SortByDescending and it will do the same?

var latestPriceChange = await _appDbContext.OfferChanges.Find(o =>
                        o.OfferId == offerListingDto.Id && o.ChangeType == OfferChangeType.PriceChange && o.IsCommited)
                    .SortByDescending(o => o.ChangeTime) // is this even needed? 
                    .FirstOrDefaultAsync();

Also, I’m trying to use async methods where possible when dealing with the I/O bound operations. Is IFindFluent interface generally preferred over AsQueryable?

IQueryable version:

 var latestPriceChange = await _appDbContext.OfferChanges
                    .AsQueryable()
                    .OrderByDescending(o => o.ChangeTime)
                    .FirstOrDefaultAsync(o => o.OfferId == offerListingDto.Id && o.ChangeType == OfferChangeType.PriceChange && o.IsCommited);

Hello @Konrad_Kogut, welcome to the MongoDB Community forum!

Do I need to do the sorting explicitly or can I safely remove SortByDescending and it will do the same?

Yes, the explicit sort (descending) on the date field is required - the first document after the sort would be the latest document.


Also, I’m trying to use async methods where possible when dealing with the I/O bound operations. Is IFindFluent interface generally preferred over AsQueryable?

I am not familiar with these methods. But, the order of the operations in the query can matter for making the query efficient. The operations should be: filter -> sort -> limit

Also, the query can be built using an Aggregation pipeline, for example (substitute appropriate field names):

db.collection.aggregate([
  { $match: { OfferId: offerListingDto.Id, ChangeType: OfferChangeType.PriceChange, IsCommited: true } },
  { $sort: { ChangeTime: -1 } },
  { $limit: 1 }
])

This query can be optimized by creating a compound index, e.g., on the filter+sort fields (see Aggregation Pipeline Optimization).

2 Likes