MongoDb c# GeoNear查询构造

本文关键字:查询 GeoNear MongoDb | 更新日期: 2023-09-27 18:13:07

如何使用c#驱动程序和GeoNear方法查询MongoDB附近的地理点?

以下返回的点的距离值不正确:

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

我怀疑我应该告诉Mongo查询双[]Location字段,但我不知道查询语法

MongoDb c# GeoNear查询构造

通过this和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
);

下面是驱动程序v2.10+的工作示例。它使用正确的地理空间点字段类型并运行$nearSphere查询。

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

YourLocationField类型应为GeoJsonPoint<GeoJson2DGeographicCoordinates>

p。您还可以为您的字段创建一个索引,以便更快地进行搜索,如下所示:

collection.Indexes.CreateManyAsync(
    new []
    {
        new CreateIndexModel<TDocument>(Builders<TDocument>.IndexKeys.Geo2DSphere(it => it.YourLocationField))
    }
);

IMongoCollection上不再有GeoNear方法。x驱动程序。这里有一个强类型和简单的方法来做$geoNear查询使用MongoDB。实体便利库。

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

上述代码向mongodb服务器发送以下查询:

db.Cafe.aggregate([
    {
        "$geoNear": {
            "near": {
                "type": "Point",
                "coordinates": [
                    48.796964,
                    2.137456
                ]
            },
            "distanceField": "DistanceMeters",
            "spherical": true,
            "maxDistance": NumberInt("20000")
        }
    }
])