Search code examples
c#mongodbmongodb-.net-driver

Use $geoWithin operator in C#


Currently in a project I am using a query to find everything in a collection within x number of miles. Reading of the mongodb docs it states that the $within operator is deprecated and that you should use the $geoWithin query operator.

I am using the Mongodb query builder (see below)

Query<Stuff>.WithinCircle(x => x.LongLat, longitude, latitude, radians, true)

and I am noticing that the query it creates uses the $within operator and not the $geoWithin operator. I am not seeing any way to update it to use the correct operator as we have upgraded to Mongodb 2.4.x


Solution

  • I don't know much about MongoDB, but it seems the mongodb-csharp code is not yet updated to use $geoWithin, as you can see here:

    mongo-csharp-driver (QueryBuilder)

    public static IMongoQuery WithinCircle(string name, double centerX, double centerY, double radius, bool spherical)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }
    
        var shape = spherical ? "$centerSphere" : "$center";
        var condition = new BsonDocument("$within", new BsonDocument(shape, new BsonArray { new BsonArray { centerX, centerY }, radius }));
        return new QueryDocument(name, condition);
    }
    

    See, it uses $within.

    Since the library is open source, you could fork, edit, and recompile it, and use your own version. Additionally, you could make a pull request to propose your changes to be included in the main code.

    I think there is no "easier" way to do it, I hope this helps.