【问题标题】:MongoDB and .netCore Find nearest locations (unable to find index for $geoNear query)MongoDB 和 .netCore 查找最近的位置(无法找到 $geoNear 查询的索引)
【发布时间】:2021-10-28 01:28:51
【问题描述】:

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

我使用 .net Core 作为 REST API。

.net Core 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 有点陌生。

让我知道如何解决这个问题(我在哪里做错了)。

【问题讨论】:

    标签: mongodb .net-core asp.net-core-webapi mongodb-geospatial


    【解决方案1】:
    _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

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

    谢谢。

    【讨论】:

      猜你喜欢
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 2023-04-01
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多