1

I am trying to do get nearest records like below but the sort operation complained to expressions not allowed. How can achieve this in MongoDB?

Error:

NotSupportedException: Only fields are allowed in a $sort. MongoDB.Driver.Linq.Translators.QueryableTranslator.TranslateOrderBy(OrderByExpression node)

Code:

public virtual List<Post> PagingNearest(Expression<Func<Post, bool>> predicate, int offset, int limit, GeoCoordinatePortable.GeoCoordinate coord)
{
    return _context.Posts.AsQueryable()
             .Where(predicate)
             .OrderBy(x => x.Location.GeoCoordinate.GetDistanceTo(coord))
             .Skip(offset)
             .Take(limit)
             .ToList();
}
Community
  • 1
  • 1
mr.byte
  • 21
  • 5
  • Are you trying to query a number of documents that contain GeoJSON coordinates, and sort them according to distance from a particular point? – kevinadi Mar 06 '18 at 05:20

1 Answers1

1

I resolved this issue by casting it to a list, then sorting and in my case once again casting the returned IOrderedEnumerable to a list.

The last case .ToList() is of course optional, it just suited my needs.

In my case I'm also ordering by a boolean value with a ternary operator.

.ToList().OrderBy(e => e.SomeBoolean ? 0 : 1).ToList();

gian848396
  • 459
  • 1
  • 8
  • 24
  • Note: If you do this you are sorting on the server instead of in the database. If you're doing any sort of Skip/Take this won't work. – JMD Feb 04 '22 at 18:43