通过查询MongoDB强类型C#分页结果组

bxpogfeg  于 2023-03-22  发布在  Go
关注(0)|答案(1)|浏览(130)

我想知道是否有人可以帮助我。我创建了一个查询,它返回由标识符分组的重复项,然后对结果集进行分页(运行良好)。
我正在寻求的建议,是关于最有效的方法来获得分页的总结果计数,同时使用相同的过滤器。可以使用计数方面和数据方面来组合查询,而不是我下面所做的方式。
工作部分

var filter = Builders<DuplicateOccurrence>.Filter.Eq(x => x.Id, occurrences.Id);

var data = await _baseRepository.DbCollection().Aggregate()
    .Match(filter)
    .SortByDescending(x => x.Identifier)
    .Group(e => e.Identifier, g => new 
    {
        Identifier= g.Key,
        Occurred = g.Select(x => new 
        {
            Id = x.Id
        })
    })
    .Skip((occurrences.CurrentPage - 1) * occurrences.PageSize)
    .Limit(occurrences.PageSize)
    .ToListAsync(cancellationToken);

获取总计数的咨询

var count = _baseRepository.DbCollection()
    .AsQueryable()
    .Where(x=> x.DetectionReportId == occurrences.DetectionReportObjectId)
    .GroupBy(s => s.Identifier)
    .Count();
elcex8rz

elcex8rz1#

如果要获取与文件服务器匹配的元素的总数,可以将查询拆分为两个。

var filter = Builders<DuplicateOccurrence>.Filter.Eq(x => x.Id, occurrences.Id);

// first create the query that will filter and group the documents
var query = await _baseRepository.DbCollection()
    .Aggregate()
    .Match(filter)
    .Group(e => e.Identifier, g => new 
    {
        Identifier= g.Key,
        Occurred = g.Select(x => new { Id = x.Id })
    });

// get the total count of documents
var totalDocs = query.Count();

// get the documents for the current page
var documents = await query
   .SortByDescending(x => x.Identifier)
   .Skip((occurrences.CurrentPage - 1) * occurrences.PageSize)
   .Limit(occurrences.PageSize)
   .ToListAsync(cancellationToken);

您也可以使用LINQ来实现相同的结果,但没有重载为组进行投影:

var query = await _baseRepository.DbCollection()
    .AsQueryable()
    .Where(x => x.Id, occurrences.Id)
    .GroupBy(e => e.Identifier);
    
var totalDocs = await query.CountAsync();

var documents = await query
    .OrderByDescending(x => x.Identifier)
    .Skip((occurrences.CurrentPage - 1) * occurrences.PageSize)
    .Take(occurrences.PageSize)
    .ToListAsync(cancellationToken)

相关问题