dextercom
dextercom

Reputation: 162

MongoDB .NET Driver ProjectionDefinition Slice method does not work

I work with a MongoDB collection in ASP.NET Core 3 application via a compatible MongoDB Driver. The document structure in my collection includes, among others, an array field (lets call it "steps"). My task is to project the collection with all its fields, while fetching the last two members of this array per document.

This is a mongo query which I run in Robo 3T:

db.getCollection('MyCollection').find({}, {"steps" : {$slice: -2}})

It works perfectly, and projects the data in the exact same way that I want it to. However, I cannot successfully copy this to my ASP.NET app.

This is how I build the projection in C#:

ProjectionDefinitionBuilder<BsonDocument> fieldsBuilder = Builders<BsonDocument>.Projection;
ProjectionDefinition<BsonDocument> stepsArrayProjection = fieldsBuilder.Slice("steps", -2);
List<MyCollectionModel> result = await myMongoService.GetDataByFilterDefinitionAsync(filter, stepsArrayProjection);

where filter is a predefined FilterDefinition<BsonDocument> that I use. When I try to run the query in my ASP.NET controller via Swagger, I get an exception, which says:

MongoDB.Driver.MongoCommandException: Command aggregate failed: Expression $slice takes at least 2 arguments, and at most 3, but 1 were passed in.

What I am trying to understand, is why is it any different from the $slice projection that I use while querying the collection in Robo 3T. It seems that I pass 2 the field name to slice, and which array members to take. Any help will be appreciated. Thanks.

Upvotes: 0

Views: 912

Answers (1)

Mahdi
Mahdi

Reputation: 3349

I don't think there is a difference and actually, the C# driver is pretty consistent with the Mongo shell command. I would do it like follows, though:

var filter = Builders<MyCollectionModel>.Filter.Empty;
var project = Builders<MyCollectionModel>.Projection.Slice(x => x.Steps, skip);
var result = context.MyMongoCollection.Find(filter).Project(project).ToList();

Upvotes: 1

Related Questions