MongoDb C# GeoNear Query Construction
Asked Answered
S

3

10

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 value:

var results = myCollection.GeoNear(
    Query.GT("ExpiresOn", now), // only recent values
    latitude,
    longitude,
    20
);

I suspect I should be telling Mongo to query on the double[] Location field, but I don't know the query syntax.

Snoddy answered 3/11, 2011 at 12:46 Comment(0)
S
15

Found the answer via this and this:

var earthRadius = 6378.0; // km
var rangeInKm = 3000.0; // km

myCollection.EnsureIndex(IndexKeys.GeoSpatial("Location"));

var near =
    Query.GT("ExpiresOn", now);

var options = GeoNearOptions
    .SetMaxDistance(rangeInKm / earthRadius /* to radians */)
    .SetSpherical(true);

var results = myCollection.GeoNear(
    near,
    request.Longitude, // note the order
    request.Latitude,  // [lng, lat]
    200,
    options
);
Snoddy answered 3/11, 2011 at 13:17 Comment(2)
What library did you use. Its not working for me. There is no definition of EnsureIndexIndividual
@Habo sorry too long ago - can't remember.Snoddy
B
1

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<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(longitude, latitude));
var filter = Builders<TDocument>.Filter.NearSphere(doc => doc.YourLocationField, point, maxGeoDistanceInKm * 1000);
var result = await collection.Find(filter).ToListAsync();

Type of YourLocationField should be GeoJsonPoint<GeoJson2DGeographicCoordinates>.

PS. Also you can create an index of your field for faster searching like this:

collection.Indexes.CreateManyAsync(
    new []
    {
        new CreateIndexModel<TDocument>(Builders<TDocument>.IndexKeys.Geo2DSphere(it => it.YourLocationField))
    }
);
Brezin answered 24/6, 2020 at 22:22 Comment(0)
C
0

there is no GeoNear method on IMongoCollection anymore in the 2.x driver. here's a strongly typed and easy way to do $geoNear queries using MongoDB.Entities convenience library.

using MongoDB.Driver;
using MongoDB.Entities;

namespace StackOverflow
{
    public class Program
    {
        public class Cafe : Entity
        {
            public string Name { get; set; }
            public Coordinates2D Location { get; set; }
            public double DistanceMeters { get; set; }
        }

        private static void Main(string[] args)
        {
            new DB("test");

            DB.Index<Cafe>()
              .Key(c => c.Location, KeyType.Geo2DSphere)
              .Create();

            (new Cafe
            {
                Name = "Coffee Bean",
                Location = new Coordinates2D(48.8539241, 2.2913515),
            }).Save();

            var searchPoint = new Coordinates2D(48.796964, 2.137456);

            var cafes = DB.GeoNear<Cafe>(
                               NearCoordinates: searchPoint,
                               DistanceField: c => c.DistanceMeters,
                               MaxDistance: 20000)
                          .ToList();
        }
    }
}

the above code sends the following query to mongodb server:

db.Cafe.aggregate([
    {
        "$geoNear": {
            "near": {
                "type": "Point",
                "coordinates": [
                    48.796964,
                    2.137456
                ]
            },
            "distanceField": "DistanceMeters",
            "spherical": true,
            "maxDistance": NumberInt("20000")
        }
    }
])
Cinderellacindi answered 22/6, 2019 at 4:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.