How to implement paging in MongoDB using .Net driver

When we fetching large set of records from a database, paging provides a mechanism to fetch just enough records for the immediate need. If you need more records, then you can skip to the next set of records. In a typical implementation, this is achieved by using two parameters.

  • What is starting index of the record from where the records need to start?
  • How many records should be returned?

Incase of MongoDB, about two items are represented by Skip and Limit. Skip represents concept of page index. Limit represents concept of page size. In your .Net application, the following code snipper shows how you can implement paging of records.

public async Task> GetAllLogsAsync(DateTime? fromTime, DateTime? toTime, 
   LogLevel? logLevel = null, string source = null, 
   int pageIndex = 0, int pageSize = int.MaxValue)
{
     var db = DbProvider.GetDatabase("MyByteDb");
     var byteLogCollection = db.GetCollection("ByteLog");
     var recordFilter = Builders.Filter.Empty;
     if (logLevel.HasValue)
     {
          recordFilter = Builders.Filter.Eq(nameof(ByteLog.LogLevel), logLevel);
     }
     var sorting = Builders.Sort.Ascending(l => l.ReportedAtTimeUtc);
     var queryOptions = new FindOptions
     {
          Sort = sorting,
          AllowDiskUse = true,
          Limit = pageSize,
          Skip = pageIndex*pageSize
      };
     var recordsCursor = await byteLogCollection.FindAsync(recordFilter, queryOptions);
     using (recordsCursor)
      {
          var records = await recordsCursor.ToListAsync();
          return records;
      }
 }

Above code is used to fetch list of log records from MongoDB collection. The code sets Limit and Skip values in query options along with sorting.

Search

Social

Weather

15.6 °C / 60.0 °F

weather conditions Clouds

Monthly Posts

Blog Tags