title: MongoDB C# Sort null values last
body: <p>I'm using the Mongo C# Driver to filter a table of data. The location (string of a city) field can be empty, and when sorting in ascending order, the results with an empty location come first. I'd like to sort anything with a location first and put those with no location (null) at the end of the list, so when sorting in ascending order, the list will always start with locations A-Z. The filter is quite complex so it uses a filter builder and it gets to the sorting here.</p>
  <p>Does anyone know of a way of telling the sort to put the null values at the end of the sort using the C# Mongo library? I'm using the very latest version of the library. I've tried all sorts: projections and coallesing the result to a null (not supported) and nothing seems to work.</p>
  <p>I could get two sets of data and glue them together but that feels really messy and perhaps my last resort.</p>
  <p>I've Googled for a long time and can't seem to find anyone who's done it.</p>
  <p>Any help appreciated.</p>
  <pre><code>var jobsResults = await collection.FindAsync(filter, new FindOptions&lt;MongoJob&gt;
  {
     Limit = criteria?.Take,
     Skip = criteria?.Skip,
     Sort = criteria?.SortByDirection == &quot;asc&quot;
        ? new SortDefinitionBuilder&lt;MongoJob&gt;().Ascending(x =&gt; x.Location)
        : new SortDefinitionBuilder&lt;MongoJob&gt;().Descending(x =&gt; x.Location),
     Collation = new Collation(&quot;en&quot;, strength: CollationStrength.Secondary)                });
  </code></pre>