MongoDb C# GeoNear Query Construction

后端 未结 3 837
悲哀的现实
悲哀的现实 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:37

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

提交回复
热议问题