GreenEyedAndy
GreenEyedAndy

Reputation: 1525

How to sort dynamically in mongodb

I have a "sort" query parameter. This maybe looking like this:

?sort=-name,+number

Now I want to read this and build a sort query for the c# MongoDB-Driver.
I thought of something like this:

var sortByList = parameters.Sort?.Split(',');
foreach (var sortBy in sortByList)
{
    if (sortBy.StartsWith('-'))
        // add to sort query decending ?!?
    else
        // add to sort query ascending ?!?
}

The only way I found so far is to build a string like "{name:-1, number:1}" and give this to the .Sort-method. But so I have build to build many strings that I really don't need.
Isn't there a way to do something like:

var sortDefinition = new SortDefintion();
var sortByList = parameters.Sort?.Split(',');
foreach (var sortBy in sortByList)
{
    if (sortBy.StartsWith('-'))
        sortDefinition.Add(sortBy.Substring(1), -1);
    else
        sortDefinition.Add(sortBy.Substring(1), 1);
}

return db.GetCollection<BsonDocument>("sortTest").Sort(sortDefintion).ToList();

Upvotes: 1

Views: 1734

Answers (1)

Markus
Markus

Reputation: 22456

You can solve it like this:

var bldr = Builders<BsonDocument>.Sort;
var sortDefinitions = sortByList.Select(x =>
{
    SortDefinition<BsonDocument> sortDef;
    var propName = x.Substring(1);
    if (x.StartsWith("-"))
        sortDef = bldr.Descending(propName);
    else
        sortDef = bldr.Ascending(propName);
    return sortDef;
});
var sortDef = bldr.Combine(sortDefinitions);
return db
  .GetCollection<BsonDocument>("sortTest")
  .Find(Builders<BsonDocument>.Filter.Empty)
  .Sort(sortDef)
  .ToList();

Above code uses a Linq Select to create a SortDefinition<BsonDocument> for each string in the list and combines these definitions into a single sort definition afterwards. This sort definition is then applied to the Find.

Upvotes: 1

Related Questions