【发布时间】:2015-11-29 18:08:31
【问题描述】:
这几天我一直在努力解决这个问题。我尝试在 C# 中运行一个非常简单的查询,它在 shell 中看起来像这样。
db.runCommand({geoNear: "items", near: {type: "Point", coordinates : [-111.283344899999, 47.4941836]}, spherical : true, distanceMultiplier: 3963.2, maxDistance : 25});
我的收藏是这样的
{
"_id" : ObjectId(),
"Title" : "arst",
"Description" : "<p>arst</p>",
"Date" : new Date("11/29/2015 09:28:15"),
"Location" : {
"type" : "Point",
"Coordinates" : [-111.28334489999998, 47.4941836]
},
"Zip" : "59405"
}
根据MongoDB C# API Docs 此处的文档,MongoDB.Driver.Builders.Query 对象现在是旧的。所以当我做这样的事情时
var point = new GeoJson2DGeographicCoordinates(double.Parse(longitude), double.Parse(latitude)) ;
var query = Query<Item>.Near(x => x.Location, new GeoJsonPoint<GeoJson2DGeographicCoordinates>(point), distance, true);
var result = collection.Find(query);
编译器抱怨它无法从 IMongoQuery 转换为 FilterDefinition。这告诉我新的 2.1 库不支持旧版 Query 构建器。但是对于我的一生,我在引用替代品的 api 文档中找不到任何地方?
谁能指出我在 2.1 C# 驱动程序中执行这个简单的地理空间查询的正确方向?我被难住了。
另外,我确实在集合上创建了一个 2dsphere 索引,如果我不这样做,shell 命令将无法工作。这是索引输出。
{
"v" : 1,
"key" : {
"Location.Coordinates" : "2dsphere"
},
"name" : "Location.Coordinates_2dsphere",
"ns" : "ppn.items",
"2dsphereIndexVersion" : 2
}
编辑
在翻阅了大量文档后,我想我找到了。所有示例仍然显示旧的 Query 方法,但新方法似乎是 Builders.Filter 命名空间的一部分。所以这个代码块似乎对我有用,
double lng = double.Parse(longitude);
double lat = double.Parse(latitude);
point = new GeoJson2DGeographicCoordinates(lng, lat);
pnt = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(point);
dis = distance * 1609.34;
fil = Builders<Item>.Filter.NearSphere(p => p.Location.Coordinates, pnt, dis);
filter = filter & fil;
var sort = Builders<Item>.Sort.Descending("Date");
// This is the actual query execution
List<Item> items = collection.Find(filter).Sort(sort).ToListAsync().Result;
这个代码块非常混乱,它是反复尝试和失败的结果。我相信我会想办法清理它。对我来说,您必须从 GeoJson2DGeographicCoordinates 创建一个 GeoJsonPoint 似乎有点冗长,但我相信这是有充分理由的。如果有人知道,请随时发表评论。非常欢迎任何有关改进此答案的建议,这是对文档的令人沮丧的挖掘,因此希望这有助于为其他人指明正确的方向。
【问题讨论】:
标签: c# mongodb geospatial spatial