1

I'm having this weird problem while using mongo to query locations near a geographical point. I notice that whenever I try filtering by $nearSphere through the C# driver the filter just returns all matches regardless of whether they're in the given range or not. What's weirder is that the same query works in the mongo shell itself and returns only the correct matches.

E.g.

I have a couple of room objects in the database that have the RoomLocation field which is a defined in the database as a type: Point(Created in the C# driver as a GeoJsonPoint object that then gets serialized). These points have the coordinates [0, 0] and [3, 3], and I'm querying from [0, 0] with max distance of 3, so the second point should not be found(These are geographical locations, so the distance should be a good few hundreds of kilometers, certainly not 3.)

The query I'm running is:

db.Rooms.find({
   "RoomLocation": 
      { $nearSphere: 
         { $geometry: { type: "Point", coordinates: [0, 0]},
           $maxDistance: 3
         }
      }
   }
)

Which works fine and only returns the [0, 0] point. However, if I run the following code in my C# project:

        FilterDefinition<GameRoom> filter = Builders<GameRoom>.Filter
                .NearSphere(room => room.RoomLocation, location.Longitude, location.Latitude, i_SearchRadius);

        IFindFluent<GameRoom, String> gameModes = Mongo.Database.GetCollection<GameRoom>("Rooms")
            .Find(filter)
            .Project(room => room._id.ToString());

And call it on location = new GeoPoint(0, 0), i_SearchRadius = 3, in the same manner as I do in the shell, then the result of this query will include both points.

The index is set up properly on the RoomLocation field.

Can anyone see some obvious mistake I'm making here? Since I'm really not sure what's going on right now.

Thanks.

1 Answers1

4

Ok, so I think I found it.

Apparently using the overload of NearSphere() that accepts 2 arguments as doubles doesn't work,

NearSphere(room => room.RoomLocation, location.Longitude, location.Latitude, i_SearchRadius);

But changing to the overload that accepts a GeoJsonPoint object with a GeoJson2DGeographicCoordinates as the generic type makes it work properly. Like this:

NearSphere(room => room.RoomLocation, new GeoJsonPoint<GeoJson2DGeographicCoordinates>(new GeoJson2DGeographicCoordinates(location.Longitude, location.Latitude)), i_SearchRadius);

Just for future reference.

Yahya
  • 3,386
  • 3
  • 22
  • 40