MongoDb C#GeoNear查询构造
如何使用C#驱动程序和MongoDb C#GeoNear查询构造,c#,mongodb,syntax,geospatial,C#,Mongodb,Syntax,Geospatial,如何使用C#驱动程序和GeoNear方法查询MongoDB附近的地理点 以下返回的点的距离值不正确: var results = myCollection.GeoNear( Query.GT("ExpiresOn", now), // only recent values latitude, longitude, 20 ); 我想我应该告诉Mongo查询双[]位置字段,但我不知道查询语法。通过和找到答案: 在2.x驱动程序中,IMongoCollection上不
GeoNear
方法查询MongoDB附近的地理点
以下返回的点的距离值不正确:
var results = myCollection.GeoNear(
Query.GT("ExpiresOn", now), // only recent values
latitude,
longitude,
20
);
我想我应该告诉Mongo查询双[]位置
字段,但我不知道查询语法。通过和找到答案:
在2.x驱动程序中,
IMongoCollection
上不再有GeoNear
方法。
下面是一种使用便利库进行$geoNear查询的强类型且简单的方法
使用MongoDB.Driver;
使用MongoDB.Entities;
命名空间堆栈溢出
{
公共课程
{
公共类咖啡馆:实体
{
公共字符串名称{get;set;}
公共坐标2D位置{get;set;}
公共双测距仪{get;set;}
}
私有静态void Main(字符串[]args)
{
新DB(“测试”);
DB.Index()
.Key(c=>c.Location,KeyType.Geo2DSphere)
.Create();
(新咖啡馆
{
Name=“咖啡豆”,
位置=新坐标2D(48.8539241,2.2913515),
}).Save();
var searchPoint=新坐标2D(48.796964,2.137456);
var cafes=DB.GeoNear(
近坐标:搜索点,
距离字段:c=>c.距离计,
最大距离:20000)
.ToList();
}
}
}
上述代码向mongodb服务器发送以下查询:
db.Cafe.aggregate([
{
“$geoNear”:{
“近”:{
“类型”:“点”,
“坐标”:[
48.796964,
2.137456
]
},
“距离字段”:“距离表”,
“球形”:正确,
“最大距离”:数字打印(“20000”)
}
}
])
以下是驱动程序v2.10+的工作示例。它使用正确的字段类型并运行查询
var经度=30d//x
var纬度=50d//Y
var点=新地理点(新地理点2地理坐标(经度、纬度));
var filter=Builders.filter.NearSphere(doc=>doc.YourLocationField,point,maxGeoDistanceInKm*1000);
var result=await collection.Find(filter.toListSync();
YourLocationField
的类型应为GeoJsonPoint
。
另外,您还可以创建字段索引,以加快搜索速度,如下所示:
collection.index.CreateManyAsync(
新[]
{
新的CreateIndexModel(Builders.IndexKeys.Geo2DSphere(it=>it.YourLocationField))
}
);
您使用了什么库。这对我不起作用。没有定义EnsureIndex@Habo对不起,太久以前-不记得了。
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
);