C#和MongoDb 2.0-NearSphere问题

时间:2019-05-01 10:37:40

标签: c# mongodb geospatial

我目前正在使用 C#在MongoDB上工作,我想知道在.NET中在/ geoNear附近如何工作。我可以在 go 中使它正常工作,但是我在与 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 = 9树:GEONEAR字段=位置maxdist = 1.79769e + 308 isNearSphere = 1 \ n排序:{} \ 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。

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

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

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

希望它可以帮助:)

最大