oatcrunch
oatcrunch

Reputation: 453

MongoDB .NET exception: Unsupported filter

I am currently using .NET wrapper for mongodb (refer following excerpt from packages.config for versions):

 <package id="mongocsharpdriver" version="2.4.2" targetFramework="net461" />
  <package id="MongoDB.Bson" version="2.4.2" targetFramework="net461" />
  <package id="MongoDB.Driver" version="2.4.2" targetFramework="net461" />
  <package id="MongoDB.Driver.Core" version="2.4.2" targetFramework="net461" />

I am trying to build a simple filter to obtain items of which location's Latitude and Longitude is within certain limits as defined by LatitudeDelta and LongitudeDelta.

bool filterAll = string.IsNullOrEmpty(username) || username == "*";

var filter = Builders<Models.MapQuery>.Filter.Where(p => (filterAll || (username == p.CreatorUsername))
                && Math.Abs(p.PinLocation.Latitude - desiredLatitude) < latitudeDelta
                && Math.Abs(p.PinLocation.Longitude - desiredLongitude) < longitudeDelta);

var queries = await db.GetCollection<Models.MapQuery>(Constants.MAP_QUERY)
                    .Find(filter)
                    .ToListAsync();

When the program executes "var queries" line, it hit an exception saying "Abs(({PinLocation.Latitude} - 3.209096)) is not supported.".

How do I fix the above exception? Otherwise, what would be the workaround if the above problem cannot be solved?

Upvotes: 0

Views: 2692

Answers (1)

BOR4
BOR4

Reputation: 630

Maby this works?

var filter = Builders<Models.MapQuery>.Filter.And(
        Builders<Models.MapQuery>.Filter.Eq(p => p.username, username),
        Builders<Models.MapQuery>.Filter.Lt(p => Math.Abs(p.PinLocation.Latitude - desiredLatitude), latitudeDelta),
        Builders<Models.MapQuery>.Filter.Lt(p => Math.Abs(p.PinLocation.Longitude - desiredLongitude), longitudeDelta));

I changed code to use built in API calls for more readability. I would suggest you do first check before even executing query.

Upvotes: 1

Related Questions