MongoDb C# GeoNear Query Construction

后端 未结 3 836
悲哀的现实
悲哀的现实 2020-12-16 19:15

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

3条回答
  •  失恋的感觉
    2020-12-16 19:19

    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()
                  .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(
                                   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")
            }
        }
    ])
    

提交回复
热议问题