mongodb c# select specific field

北慕城南 提交于 2019-12-22 12:27:15

问题


Need some help creating a generic method for selecting fields by their name.

something like this:

T GetDocField<T>(string doc_Id, string fieldName)

The best I got is using projection which gives me the doc with only the wanted field seted:

 public T GetDocField<T>(string Doc_Id, string fieldName)
 {
    var value = DocCollection.Find(d => d.Id == Doc_Id)
               .Project<T>(Builders<Doc>.Projection
               .Include(new StringFieldDefinition<Doc>
               (fieldName))).FirstOrDefaultAsync().Result;

note: I'm using the new c# driver (2.0)

Thanks!!


回答1:


You can do next:

public async Task<TValue> GetFieldValue<TEntity, TValue>(string id, Expression<Func<TEntity, TValue>> fieldExpression) where TEntity : IEntity
{
    var propertyValue = await collection
        .Find(d => d.Id == id)
        .Project(new ProjectionDefinitionBuilder<TEntity>().Expression(fieldExpression))
        .FirstOrDefaultAsync();

    return propertyValue;
}

and call it

var value = await GetFieldValue<Item, string>("111", x => x.Name);


来源:https://stackoverflow.com/questions/31143586/mongodb-c-sharp-select-specific-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!