Wax*_*ren 1 .net c# mongodb mongodb-query mongodb-.net-driver
我正在使用官方 C# MongoDb 强类型驱动程序版本 2.5.0 与 MongoDB 交互。
我有一个经度和纬度坐标数组,我想将它们存储在 MongoDB 中。
用于存储坐标数组的类的名称是什么?所以我最近可以执行以下查询,检查如果给定坐标靠近坐标数组中的任何点,如何实现这一点?
这是演示该问题的简单代码。
var coordinates = new List<(double latitude, double longitude)>();
//Store coordinates array in the database
(double latitude, double longitude) point = (-33.847927, 150.6517805);
int maxDistance = 300;//Max Distance in meters
//Check if any point in the coordinates array is 300 m near the given point
Run Code Online (Sandbox Code Playgroud)
编辑:-
根据下面@CodeFuller评论中提到的这个问题:-
数组上的 MongoDB 地理空间索引(多键 + 地理空间)
MongoDB 不支持数组上的地理空间索引,因此请考虑以下类:
class SomeDocument {
public ObjectId Id { get; set; }
public string Title { get; set; }
public List<MyClass> Locations {get; set;} = new List<MyClass>();
}
class MyClass {
public ObjectId Id { get; set; }
public GeoJsonPoint<GeoJson2DGeographicCoordinates> Location { get; set;
}
Run Code Online (Sandbox Code Playgroud)
如何获取在给定点附近至少有一个点的 SomeDocument 的所有实例?并按最接近的对它们进行排序?
MongoDB .NET Driver 提供了MongoDB.Driver.GeoJsonObjectModel.GeoJson2DGeographicCoordinates2D 地理坐标类。
这是基本用法:
在模型类中定义属性GeoJsonPoint<GeoJson2DGeographicCoordinates>类型:
public class SomeDocument
{
public ObjectId Id { get; set; }
public string Title { get; set; }
public GeoJsonPoint<GeoJson2DGeographicCoordinates> Location { get; set; }
}
Run Code Online (Sandbox Code Playgroud)确保您有2dsphere(或2d,取决于您的需要)Location字段索引。您可以通过 mongo 客户端创建和索引:
db.testCollection.createIndex( { 位置: "2dsphere" } );
或者通过 MongoDB .NET 驱动程序:
var database = mongoClient.GetDatabase("testDB");
IMongoCollection<SomeDocument> collection = database.GetCollection<SomeDocument>("testCollection");
collection.Indexes.CreateOne(new IndexKeysDefinitionBuilder<SomeDocument>().Geo2DSphere(x => x.Location));
Run Code Online (Sandbox Code Playgroud)插入数据:
collection.InsertOne(new SomeDocument
{
Title = "Place #1",
Location = GeoJson.Point(new GeoJson2DGeographicCoordinates(145.89, -35.83)),
});
collection.InsertOne(new SomeDocument
{
Title = "Place #2",
Location = GeoJson.Point(new GeoJson2DGeographicCoordinates(154.98, -53.38)),
});
Run Code Online (Sandbox Code Playgroud)
请注意,在 MongoDB 中,您首先指定经度。
寻找邻居:
var point = GeoJson.Point(new GeoJson2DGeographicCoordinates(145.889, -35.831));
int maxDistance = 300;
IAsyncCursor<SomeDocument> cursor = collection.FindSync(new FilterDefinitionBuilder<SomeDocument>().Near(x => x.Location, point, maxDistance: maxDistance));
// Check whether at least one is near the point
var hasNeighbors = cursor.Any();
Run Code Online (Sandbox Code Playgroud)