简体   繁体   中英

How do I programmatically set the sort field on a MongoDB query using the C# driver?

I have a collection of Tool objects, which I want to optionally filter, and return into a paginated table on a web page. I've got it working with the filter and the pagination, but I'm having trouble with the sort. I'm using an Angular Material table, which lets the user chose the sort field and direction at run time.

Using the MongoDB C# driver, I built a collection of tools which match theFilter, (fo = find options = case insensitive). Skip and Limit provide the pagination - I do know that's not necessarily efficient for big collections, that is not a concern here - and ToList sends it to the API.

tools = _tools.Find<Tool>(theFilter, fo)
    .Sort(Builders<Tool>.Sort.Descending(x => x.Description))
    .Skip(pageNo * pageSize)
    .Limit(pageSize)
    .ToList();

In that example, the Sort call correctly sorts the collection in descending order by the description field. I need to be able, at run time, to chose a different field (eg x.id , x.Name , x.location , x.whatever ), and to be able to switch between descending and ascending order.

Attempts to use MongoDB's syntax:

    .Sort("{ description: -1}")

fail, as does attempting to build a SortDefinition object using the field's name:

    private SortDefinition<T> BuildSortDefinition<T>(string fieldName, string sortDirection)
    {
        FieldDefinition<T> theField = new StringFieldDefinition<T>(fieldName);
        SortDefinition<T> theSort;

        if (sortDirection.ToLower() == "desc")
            theSort = Builders<T>.Sort.Descending(theField);
        else
            theSort = Builders<T>.Sort.Ascending(theField);

        return theSort;
    }

I've only been able to make Sort work if I use a lambda expression. How can I either fix the lambda expression to use a configurable field; or use the .Sort properly in order to use a configurable field, in this scenario?

My problem was using the wrong casing for the search field - "description" instead of "Description". Once I passed the correct case, it worked fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM