1

I'm trying to find nearest other locations form my MongoDB database.

I'm using .net Core as rest API.

.net Core 5.0

This is my MDB Class

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

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

}

This is the way I fond to make the query (To find nearest other locations within 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 is Injected with a interface and it represents IMongoCollection.

My objects are saving perfectly find in the database (DB connection is fine). enter image description here

But When I try to find other near location this error comes.

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.'

In this Line

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

enter image description here

I'm bit new to .net core and MongoDB.

Let me know how to fix this issue (Where I make my wrong turn).

gamal
  • 1,587
  • 2
  • 21
  • 43

1 Answers1

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

This fixed my issue.

I put it before this.

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

I found the solution form -> MongoDb C# GeoNear Query Construction

Please, Anyone who knows the reason explain.

Thank you.

gamal
  • 1,587
  • 2
  • 21
  • 43