How do you project on fields in the new MongoDB C# drivers when the fields are given in the form of a String array ?. I could find ways to project on a single field by doing
collection.find(filter).Project(Builders<Category>.Projection.Include(fieldName)
How do I extend this to take an array of fields ?.
There is also extension method Include
var projection = Builders<Category>.Projection.Include(fieldList.First());
foreach (var field in fieldList.Skip(1))
{
projection = projection.Include(field);
}
var result = await collection.Find(filter).Project(projection).ToListAsync();
another way, assuming fieldList is a string enumerable is:
var project = Builders<BsonDocument>.Projection.Combine(fieldList.Select(x => Builders<BsonDocument>.Projection.Include(x)).ToList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With