How do I query MongoDB for nearby geographic points using the C# driver and the GeoNear
method?
The following returns points with an incorrect Distance
Here is a working example for driver v2.10+. It uses a correct geospatial point field type and runs $nearSphere query.
var longitude = 30d; //x
var latitude= 50d; //y
var point = new GeoJsonPoint(new GeoJson2DGeographicCoordinates(longitude, latitude));
var filter = Builders.Filter.NearSphere(doc => doc.YourLocationField, point, maxGeoDistanceInKm * 1000);
var result = await collection.Find(filter).ToListAsync();
Type of YourLocationField
should be GeoJsonPoint
.
PS. Also you can create an index of your field for faster searching like this:
collection.Indexes.CreateManyAsync(
new []
{
new CreateIndexModel(Builders.IndexKeys.Geo2DSphere(it => it.YourLocationField))
}
);