Search code examples
c#mongodblambdamongodb-querymongodb-.net-driver

Is there any possibility to sort MongoDB results using a lambda expression


I have an interface with multiple implementations and one of the implementation is using Mongo DB. The method that I am trying to implement has a paramenter a lambda expression which I need to use it to sort the data found in MongoDB. For sorting, MongoDB requires a SortDefinition, but all I have is lambda expression. Can I convert this lambda expression into a SortDefinition somehow?

public IEnumerable<Car> GetDataSorted(Expression<Func<Car,string>> sortCriteria)
{
    var result = _mongoDBCollection.Find(filterCriteria);
    return result.sort(sortCriteria).ToList();
}

For this specific code I am receving an error saying that cannot convert lambda expression to SortDefinition.


Solution

  • You can read your Expression to get field name and then build your sortDefinition as BsonDocumentSortDefinition<T>:

    var body = sortCriteria.Body.ToString();
    var parameter = sortCriteria.Parameters.First() + ".";
    var fieldPath = body.Substring(parameter.Length);
    
    SortDefinition<Car> sortDefinition = new BsonDocumentSortDefinition<Car>(
        new BsonDocument(){ { fieldPath, 1 } });
    
    return result.Sort(sortDefinition).ToList();
    

    It works for below cases:

    r.GetDataSorted(c => c.Name); // evaluates to Name
    r.GetDataSorted(car => car.Name); // evaluates to Name
    r.GetDataSorted(car => car.Nested.Field); // evaluates to Nested.Field