C# MongoDB 驱动程序 2.0 - 从近查询获取距离

本文关键字:查询 获取 距离 MongoDB 驱动程序 | 更新日期: 2023-09-27 17:56:27

我正在使用C# MongoDB驱动程序2.0进行NearSphere查询,它工作正常。结果自动按距离排序,但我希望为每个搜索结果返回该距离,以便能够显示它。我发现这篇文章说如何为旧版本的驱动程序执行此操作 从 Near 查询中检索距离"dis"结果,但没有设法找到如何使用新驱动程序执行此操作。

这是我的代码:

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 之前我必须做点什么?

有什么帮助吗?

多谢

C# MongoDB 驱动程序 2.0 - 从近查询获取距离

C# MongoDB 驱动程序缺少一些操作,但实际上查询数据库没有任何限制。Project、Match 等方法只是构建一个 PipeLine 的帮助程序,该管道线与其他任何 BsonDocument 一样。

我不得不使用与您类似的方法从 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
        }
    }
}

我希望它有所帮助。