使用 MongoDB .Net 驱动程序对存储在文档字段中的数组进行分页

Pagination on array stored in a document field using MongoDB .Net Driver

如何使用带有 MongoDB .Net 驱动程序的 C# 在 animals 字段中应用分页?

架构是:

[{
    id: 1,
    name: "Tom",
    animals: ["cat", "dog", "fish", "bear", "dog1", "fish1", "bear1",]
},
{
    id: 2,
    name: "Rob",
    animals: ["shark", "snake", "fish", "bear", "panda"]
},
{
    id: 3,
    name: "Matt",
    animals: ["cat", "fish", "bear"]
}]

给出了解决方案 但我发现它很难在 C# 中实现。

下面是我的代码

var bsonSearchParams = new BsonDocument {
    new BsonElement ( "id" , id),
    new BsonElement  ( "animals", "{ $slice: [ 0, 3 ] }" )
};
var result = await collection.Find(bsonSearchParams).FirstOrDefaultAsync();
return result;

期待结果

{
    id: 1,
    name: "Tom",
    animals: ["cat", "dog", "fish"]
}

您的 bsonSearchParams 不正确,因为您在投影中包含了 slice 逻辑。

您需要 .Slice(),这是 ProjectDefinition 的扩展方法。

public static ProjectionDefinition<TDocument> Slice<TDocument>(this ProjectionDefinition<TDocument> projection, FieldDefinition<TDocument> field, int skip, int? limit = null)

您的源代码应如下所示:

var bsonSearchParams = new BsonDocument 
{
    new BsonElement( "id" , id)
};

var bsonProjection = Builders<BsonDocument>.Projection
    .Slice("animals", 0, 3);

var result = await collection.Find(bsonSearchParams)
    .Project(bsonProjection)
    .FirstOrDefaultAsync();

Sample code & output