Project on multiple fields in C# MongoDB 2.0

Adarsh picture Adarsh · Jul 8, 2015 · Viewed 7.4k times · Source

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 ?.

Answer

rnofenko picture rnofenko · Jul 8, 2015

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();