首页 > 解决方案 > 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。

谢谢你的帮助

标签: c#mongodbgeospatial

解决方案


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

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;
    }
}

希望它可以帮助:)

最大限度


推荐阅读