C# mongo 附近查询无法找到 $geoNear 的索引

标签 c# mongodb

我在我的 Mongo 数据库上创建了以下索引

db.AddressInformations.createIndex({"Address.Gps" : "2dsphere"}, {bits:26})

在 mongo shell 中我可以运行它并且它有效

db.AddressInformations.find({"Address.Gps": {
$near: {
    $geometry:{ 
        type: "Point", 
        coordinates: [-84.26060492426588, 30.45023887165371]
    }
}
}})

但是,如果我尝试运行其中任何一个

db.AddressInformations.find({"Address.Gps" : {$geoNear:[-81.941429, 26.639506]}})

db.AddressInformations.find({"Address.Gps" : {$near:[-81.941429, 26.639506]}})

我收到这个错误

unable to find index for $geoNear query

在我的 C# 代码中,我也尝试运行此查询并得到相同的错误

var query = Builders<BsonDocument>.Filter.Near("Address.Gps",
             GeoJson.Point(GeoJson.Geographic(lon, lat)));

var returnItems = await MongoCollection.FindAsync(query, findOptions, 
                         cancellationToken.Token);

return await returnItems.ToListAsync(cancellationToken.Token);

最佳答案

C# MongoDB 有一定的局限性,与 MongoDB shell 相比,通常在功能方面落后。

尝试以下代码片段:

var query = "{'Address.Gps': {$near: {$geometry:{type: 'Point', coordinates: [-84.26060492426588, 30.45023887165371]}}}}";

var filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument> (query);

var result = db.AddressInformations.find(filter);

在这里,我将 MonogoDB shell 查询转换为 BsonDocument,并将其用作 C# 集合 API 的过滤器。

我过去曾向 MongoDB 提交过功能请求。见https://jira.mongodb.org/browse/CSHARP-1585

关于C# mongo 附近查询无法找到 $geoNear 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966174/

相关文章:

c# - 如何在单元测试中验证EF Core DBContext配置

c# - 右侧模糊的 WPF 列表框边框

json - 解码 JSON 保留空值

mongodb - 使用specs2玩!使用 Reactivemongo 的虚假应用程序会导致超时

java - 如何在 REST Web 服务中使用 json 生成 http 响应?

c# - 从墓碑返回时 RootVisual 为空?

c# - Convert.ToInt32 与 TryParse

mongodb - 安装 mongodb 版本 >3 树莓派 2

javascript - 将mongoose返回的数据转换为json

c# - 将两种方法重构为一种