2015-06-16 71 views
1

我正在用C#MongoDB驅動程序2.0進行NearSphere查詢,它工作正常。 結果是按距離自動排序的,但我希望能夠找回每個搜索結果的距離以便能夠將其顯示回來。 我發現這篇文章說如何做的舊版驅動程序Retrieving the Distance "dis" result from a Near query但沒有設法找到如何與新的驅動程序。C#MongoDB驅動程序2.0 - 從近查詢獲取距離

這是我的代碼:

var collection = database.GetCollection<MyType>("myTypes"); 
var locFilter = Builders<MyType>.Filter.NearSphere(x => x.GeoLocation, criteria.Long, criteria.Lat, criteria.RadiusInMiles/3963.2); 
var results = await collection.Find(locFilter).ToListAsync(); 

我想我對IFindFluent結果調用ToList之前做一些事情?

任何幫助?

非常感謝

+0

這裏(底層)實現的基本[**'$ near' **](http://docs.mongodb.org/manual/reference/operator/query/near/)運算符不會返回距離點或物體的「距離」。您可能需要使用更直接的調用方法:1:聚合[**'$ geoNear' **](http://docs.mongodb.org/manual/reference/operator/aggregation/geoNear/)或2 :[** geoNear **](http://docs.mongodb.org/manual/reference/command/geoNear/)數據庫命令表單,它們都返回距離作爲返回文檔中的字段結果 –

+0

感謝您的幫助!儘管如此,我正在努力尋找使用C#2.0驅動程序的方式。如果你有一個例子,將不勝感激。謝謝 –

+0

現在只是讓我現在因爲評論反對「答案」,因爲我要睡覺了。所有驅動程序都支持提交'.aggregate()'管道或基本的'db.command'語句的基本方法,如果你只是尋找方法 –

回答

3

的C#MongoDB的驅動程序缺少一些操作的,但現實有沒有任何限制查詢數據庫。 Project,Match等方法只是幫助您構建一個與其他任何BsonDocument完全相同的PipeLine。

我有使用類似的方法來你查詢到C#數據庫:

db.mycoll.aggregate( 
[ { $geoNear : 
    { near : { type : "Point", coordinates : [-34.5460069,-58.48894900000001] }, 
    distanceField : "dist.calculated", maxDistance : 100, 
    includeLocs : "dist.location", 
    num : 5, spherical : true } 
    } , 
    { $project : {_id: 1, place_id:1, name:1, dist:1} } 
]).pretty() 

正如你所知道有沒有一個geoNear方法來建立它的驅動程序,所以你可以創建BsonDocument。 爲了向您展示一切都可以用這種方式構建,請從C#中找到一個示例查詢,而不是使用項目clausule,我從BsonDocument構建它。您可以根據需要推送BsonDocument。

var coll = _database.GetCollection<UrbanEntity>("mycoll"); 
var geoNearOptions = new BsonDocument { 
    { "near", new BsonDocument { 
     { "type", "Point" }, 
     { "coordinates", new BsonArray {-34.5460069,-58.48894900000001} }, 
     } }, 
    { "distanceField", "dist.calculated" }, 
    { "maxDistance", 100 }, 
    { "includeLocs", "dist.location" }, 
    { "num", 5 }, 
    { "spherical" , true } 
}; 

var projectOptions = new BsonDocument { 
    { "_id" , 1 }, 
    { "place_id", 1 }, 
    { "name" , 1 }, 
    { "dist", 1} 
}; 

var pipeline = new List<BsonDocument>(); 
pipeline.Add(new BsonDocument { {"$geoNear", geoNearOptions} }); 
pipeline.Add(new BsonDocument { {"$project", projectOptions} }); 

using(var cursor = await coll.AggregateAsync<BsonDocument>(pipeline)) { 
    while(await cursor.MoveNextAsync()) { 
     foreach (var doc in cursor.Current) { 
      // Here you have the documents ready to read 
     } 
    } 
} 

我希望它有幫助。

相關問題