2015-06-16 153 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 
     } 
    } 
} 

我希望它有帮助。

相关问题