地理空间查询在 mongo shell 中查找,但在 C# 驱动程序中不过滤

本文关键字:但在 驱动程序 过滤 查找 查询 空间 mongo shell | 更新日期: 2023-09-27 17:56:49

我在使用 mongo 查询地理点附近的位置时遇到了这个奇怪的问题。我注意到,每当我尝试通过 C# 驱动程序按$nearSphere进行筛选时,过滤器都会返回所有匹配项,无论它们是否在给定范围内。更奇怪的是,相同的查询在 mongo shell 本身中工作,并且只返回正确的匹配项。

例如

我在数据库中有几个房间对象,这些对象具有 RoomLocation 字段,该字段在数据库中定义为类型:Point(在 C# 驱动程序中创建为 GeoJsonPoint 对象,然后被序列化)。这些点的坐标为 [0, 0] 和 [3, 3],我从 [0, 0] 查询,最大距离为 3,所以应该找不到第二个点(这些是地理位置,所以距离应该是几百公里,当然不是 3。

我正在运行的查询是:

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

它工作正常,只返回 [0, 0] 点。但是,如果我在 C# 项目中运行以下代码:

        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());

并在位置 = new GeoPoint(0, 0) i_SearchRadius = 3 调用它,方式与我在 shell 中调用的方式相同,则此查询的结果将包括这两个点。

索引在"房间位置"字段中设置正确。

谁能看到我在这里犯的一些明显的错误?因为我真的不确定现在发生了什么。

谢谢。

地理空间查询在 mongo shell 中查找,但在 C# 驱动程序中不过滤

好的,所以我想我找到了。

显然,使用 NearSphere() 的重载接受 2 个参数作为双精度是行不通的,

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

但是更改为接受具有 GeoJson2DGeographicT坐标作为泛型类型的 GeoJsonPoint 对象的重载可以使其正常工作。喜欢这个:

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

仅供将来参考。

相关文章: