1

我正在尝试从我的 MongoDB 数据库中找到最近的其他位置。

我正在使用 .net Core 作为休息 API。

.net 核心 5.0

这是我的 MDB 类

public class MdbTrip
{
        [BsonId]
        [BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
        public string id { get; set; }

        public GeoJsonPoint<GeoJson2DGeographicCoordinates> location { get; set; }

}

这是我喜欢进行查询的方式(查找 200m 内最近的其他位置)。

 var point = GeoJson.Point(GeoJson.Geographic(myLocation.lng, myLocation.lat));
 var locationQuery = new FilterDefinitionBuilder<MdbTrip>().Near(tag => tag.location, point, 200);
 var c = _trips.Find(locationQuery).ToList();

_trips 被注入一个接口,它代表 IMongoCollection。

我的对象完美保存在数据库中(数据库连接很好)。 在此处输入图像描述

但是当我试图找到其他附近的位置时,就会出现这个错误。

MongoDB.Driver.MongoCommandException: 'Command find failed: error processing query: ns=VtrackDB.MdbTripTree: GEONEAR  field=location maxdist=200 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error :: caused by :: unable to find index for $geoNear query.'

在这条线上

var c = _trips.Find(locationQuery).ToList();

在此处输入图像描述

我对 .net core 和 MongoDB 有点陌生。

让我知道如何解决这个问题(我犯错的地方)。

4

1 回答 1

0
_trips.Indexes.CreateManyAsync(
    new[]
    {
        new CreateIndexModel<MdbTrip>(Builders<MdbTrip>.IndexKeys.Geo2DSphere(it => it.location))
    }
);

这解决了我的问题。

我把它放在这之前。

var point = GeoJson.Point(GeoJson.Geographic(myLocation.lng, myLocation.lat));

我找到了解决方案表格-> MongoDb C# GeoNear Query Construction

请知道原因的人解释一下。

谢谢你。

于 2021-08-28T18:13:48.477 回答