c# - C# & MongoDb 2.0 - NearSphere 问题
问题描述
我目前正在使用C#开发 MongoDB,我想知道如何在 .NET 中使用 near/geoNear。我可以让它工作,但我正在努力使用C#
在去我有以下内容:
var addresses []*models.Address
bson.M{
"location": bson.M{
"$near": bson.M{
"$geometry": bson.M{
"type": "Point",
"coordinates": []float64{ in.Area.Longitude, in.Area.Latitude },
},
"$maxDistance": in.Area.Scope,
},
},
}, &addresses)
现在在C#中,我有以下内容:
var options = new FindOptions<SchoolDataModel> { Limit = 10 }; // Just because I wanna limit to 10 results
var filter = NewFilterBuilder().NearSphere(s => s.Location, in.Area.Longitude, in.Area.Latitude);
return await (await GetCollection<AddressDataModel>().FindAsync(filter, options)).ToListAsync();
然后我得到以下信息:
"ExceptionMessage": "命令查找失败:错误处理查询:ns=eyesapp.SchoolDataModel limit=9Tree: GEONEAR field=Location maxdist=1.79769e+308 isNearSphere=1\nSort: {}\nProj: {}\n planner 返回错误: 无法找到 $geoNear 查询的索引。”
我知道我必须创建一个索引,所以我在C#中尝试了同样的方法:
await GetMongoDatabase()
.GetCollection<AddressDataModel>(typeof(AddressDataModel).Name)
.Indexes.CreateOneAsync(new CreateIndexModel<AddressDataModel>(Builders<AddressDataModel>.IndexKeys.Geo2DSphere(x => x.Location)));
但是,在尝试创建索引时启动 ASP.NET 应用程序时出现以下异常:
{“命令 createIndexes 失败:无法提取地理键:{ _id: ObjectId .... }。”}
最后,我想要实现的是,就像在Go中一样,能够找到给定位置附近的地址,具有最大距离,但也具有预定义的限制,例如 10、20 或 50。
谢谢你的帮助
解决方案
事实证明,除了位置本身的存储之外,一切都很好。在我的数据模型中,我有以下内容:
public class Location
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
但是我错了,下面的类是存储位置的正确方法
public class Location
{
[BsonElement("type")]
public string Type { get; } = "Point";
[BsonElement("coordinates")]
public double[] Coordinates { get; set; } = new double[2] { 0.0, 0.0 };
public double Latitude
{
get => Coordinates[1];
set => Coordinates[1] = value;
}
public double Longitude
{
get => Coordinates[0];
set => Coordinates[0] = value;
}
}
希望它可以帮助:)
最大限度
推荐阅读
- radio-button - 角度材料 7:无法使用键盘正确选择组件内的单选按钮
- javascript - 在显示它的同时还打印来自本地存储的旧数据
- elasticsearch - 按子串匹配
- php - 条纹创建直接费用以连接帐户
- java - Java Exception 没有从 db2 控制台返回的相同异常消息?
- sql-server - 使用游标,如何处理 SQL 中的错误
- azure - 具有 Guid 74af9f20-af6a-5582-9382-f21f674fb271 的 EventSource 实例已存在
- google-cloud-platform - X区没有足够的资源
- javascript - 通过 appendChild() 附加的孩子不显示
- file - 复制文件后的修改时间