Include/Exclude fields in query with MongoDB C# driver 2.4

I had a similar issue, I believe you need to specify the generic type, for some reason Project automatically assumes BsonDocument. This should fix it from BsonDocument to your class.

Change:

var allDocs = collection.Find().Project(fields).ToList();

To:

var allDocs = collection.Find<MyDoc>().Project<MyDoc>(fields).ToList();

As for how to include only certain fields, this can be done just as you are doing it with builder (using Include) or with a string in json form like:

var allDocs = collection.Find<MyDoc>().Project<MyDoc>("{Prop1: 1, Prop2: 1}").ToList();

I would highly recommend checking out projection on this guy's post: https://www.codementor.io/pmbanugo/working-with-mongodb-in-net-part-3-skip-sort-limit-and-projections-oqfwncyka

From this article:

This brings us to another difference: with a projection definition, it implicitly converts the document type from Student to BsonDocument, so what we get back is a fluent object that, in result, will be a BsonDocument (even though what we're working with is the Student type). If we want to work with Student, we have to indicate that we still want to keep the type to Student.


A newer way:

var fieldsBuilder = Builders<MyDoc>.Projection;
var fields = fieldsBuilder.Exclude(d => d.BigField1).Exclude(d => d.BigField2);

return Collection.Find(x => x.id.Equals(id)).Project<MyDoc>(fields).ToEnumerable();

Gina