我目前正在与MongoDB C#合作,我想知道在.NET的near/geoNear是如何工作的。
在go中,我有以下内容:
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计划器返回错误:无法为$geoNear查询找到索引”。
我知道在go中,我必须创建一个索引,所以我在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。
谢谢你的帮助
发布于 2019-05-02 11:03:46
事实证明,一切都很好,除了地点本身的存储。在我的数据模型中,我有以下内容:
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;
}
}希望它能有所帮助:)
最大值
https://stackoverflow.com/questions/55934904
复制相似问题