Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project on multiple fields in C# MongoDB 2.0

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

like image 957
Adarsh Avatar asked Oct 24 '25 11:10

Adarsh


2 Answers

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();
like image 149
rnofenko Avatar answered Oct 27 '25 00:10

rnofenko


another way, assuming fieldList is a string enumerable is:

var project = Builders<BsonDocument>.Projection.Combine(fieldList.Select(x => Builders<BsonDocument>.Projection.Include(x)).ToList());
like image 45
FDB Avatar answered Oct 27 '25 01:10

FDB