1. 程式人生 > >c# 在mongo中查詢經緯度範圍

c# 在mongo中查詢經緯度範圍

lis region reat 數據 index all 坐標計算 list() key


#region 索引

//IndexKeysDocument doc = new IndexKeysDocument();//新建索引

//2d 平面坐標索引,適用於基於平面的坐標計算。也支持球面距離計算,不過官方推薦使用2dsphere索引
//BsonValue value = BsonValue.Create("2d");//創建2d索引

//2dsphere 幾何球體索引,適用於球面幾何運算
//不過,只要坐標跨度不太大(比如幾百幾千公裏),這兩個索引計算出的距離相差幾乎可以忽略不計
//BsonValue value = BsonValue.Create("2dsphere");//創建2d索引

//doc.Add("loc", value);//loc為數據庫中2d索引的對象名稱
//table.CreateIndex(doc);//創建索引

#endregion

double y = 26.0623344427;
double x = 119.2916107177;
double maxDistance = 0.5;//單位:公裏(千米)
double earchR = 6378137 / 1000.0;//6378137:地球半徑,單位:米
double distance = maxDistance / earchR;

IMongoQuery query = Query.WithinCircle("loc", x, y, distance, true);

IMongoQuery query1 = Query.Near("loc", x, y, distance, true);

var _location = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(x, y));
IMongoQuery query2 = Query.Near("loc", _location, distance, true);

ConcurrentBag<double> bags = new ConcurrentBag<double>();

double totaletime = 0;
int max = 1000;
Parallel.For(0, max, (i) =>
{
    DateTime start = DateTime.Now;
    var finds = table.Find(query1).AsQueryable().ToList();
   
    double etime = (DateTime.Now - start).TotalSeconds;
    bags.Add(etime);
});

c# 在mongo中查詢經緯度範圍