MongoDb C# GeoNear Query Construction

烂漫一生 提交于 2020-02-13 04:47: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 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.


回答1:


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
);



回答2:


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


来源:https://stackoverflow.com/questions/7995097/mongodb-c-sharp-geonear-query-construction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!