I am creating a projection variable like this:
var projection = Builders<Items>.Projection
.Include(x => x.Name);
The Include
method takes an expression Expression<Func<TSource,object>> field
.
What I would like to do is to convert a string parameter named key
for example to x.Name
, to be able to dynamically project other fields of Items
at runtime.
var key = "Name";
var projection = Builders<Items>.Projection
.Include(x => x."key");
CodePudding user response:
As written this answer from the comment as the future reference, you can apply
.Include(key)
Provide a string
value which is the field name.
As from ProjectDefinition<TDocument>.Include<TDocument>()
, it supports with the parameter of FieldDefinition
type,
public static ProjectionDefinition<TDocument> Include<TDocument>(this ProjectionDefinition<TDocument> projection, FieldDefinition<TDocument> field)
which FieldDefinition<TDocument>
would perform an implicit cast from the string
value.
public static implicit operator FieldDefinition<TDocument>(string fieldName)