MongoDb C# 分页写法-10

int pageIndex=0;
int pageSize=10;
PipelineDefinition<BsonDocument, BsonDocument> pipeline = new BsonDocument[]
{
    new BsonDocument("$match", new BsonDocument()
        .Add("UserName", "张三")
        .Add("Sex", "male")
    new BsonDocument("$project", new BsonDocument()
        .Add("UserName", 1.0)),
    new BsonDocument("$skip", pageIndex*pageSize),
    new BsonDocument("$limit", pageSize)
};
database.GetCollection<BsonDocument>("user").Aggregate<BsonDocument>(pipeline).ToList();

示例:获取第一个分页数据(分页大小10),上面代码拿到的是最外层分页,如果想拿User中的,需要在$project后使用Unwind

new BsonDocument("$unwind", new BsonDocument()
                        .Add("path", "$StudentList")), 

这样的话拿到的数据才是学生列表数据

如果需要获取总个数,可以写两个pipleline,去掉$skip,$limit加一句

new BsonDocument("$count", "totalCount")  

int totalCount = 0 ;
var totoalResult=collection.Aggregate<BsonDocument>(pipelineTotal).FirstOrDefault();
if (totoalResult != null)
{
    totoalResult.TryGetValue("totalCount", out BsonValue bsonValue);
    totalCount = bsonValue.AsInt32;
}

totalCount即为总数据  

1、建了一个小群:616945527(软件), 欢迎大家加入,加群口令abc123,硬件嵌入式开发者推荐75764412(单片机)。
闲置域名www.nsxz.com出售(等宽等高字符四字域名,可组合多种有意义词语)。
原文地址:https://www.cnblogs.com/zhaogaojian/p/14349594.html