首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# & MongoDb 2.0 - NearSphere发行

C# & MongoDb 2.0 - NearSphere发行
EN

Stack Overflow用户
提问于 2019-05-01 10:37:40
回答 1查看 117关注 0票数 0

我目前正在与MongoDB C#合作,我想知道在.NET的near/geoNear是如何工作的。

go中,我有以下内容:

代码语言:javascript
复制
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#,我有以下内容:

代码语言:javascript
复制
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#中尝试了同样的方法

代码语言:javascript
复制
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。

谢谢你的帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-02 11:03:46

事实证明,一切都很好,除了地点本身的存储。在我的数据模型中,我有以下内容:

代码语言:javascript
复制
public class Location
{
    public double Latitude { get; set; }

    public double Longitude { get; set; }
}

但是我错了,下面的课是存储位置的正确方法。

代码语言:javascript
复制
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;
    }
}

希望它能有所帮助:)

最大值

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55934904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档