【问题标题】:C# MongoDB "Near" QueryC# MongoDB“近”查询
【发布时间】:2013-01-18 11:48:14
【问题描述】:

我有一个看起来像这样的 mongo 集合:

{
"_id": {
    "$oid": "50e9f38fbd7680c8090bcb4"
},
"guid": "D3G5wQ8RZL",
"lat": 37.503287248864,
"lng": -121.97620341421,

} 我想使用 C# linq 执行“NEAR”查询

它需要看起来像这样

query = query.Where(x => LinqToMongo.Inject(Query.Near("Location", -96.770401, 32.816774, 20)));

我的问题是 - 我应该对“位置”进行编码吗?如何查看以上集合中的积分?

谢谢。

【问题讨论】:

    标签: linq c#-4.0 collections mongodb-.net-driver


    【解决方案1】:

    从 MongoDB 2.4 开始,存储和索引 GeoJSON。你可以找到所有的概念here

    如何在 POCO 类型上定义 GeoJSON 属性:

    public class Foo
    {
      public GeoJsonPoint<GeoJson2DGeographicCoordinates> Location { get; set; }
    }
    

    实例化示例:

    var docToInsert = new Foo
                {   
                    Location = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(
                        new GeoJson2DGeographicCoordinates(-121.97620341421, 37.503287248864))
                });
    

    $near 需要一个地理空间索引,由于我们存储的是 GeoJSON,它特别需要一个 2dsphere 索引:

    var collection = //get MongoCollection<Foo> from MongoDatabase object
    collection.EnsureIndex(IndexKeys<Foo>.GeoSpatialSpherical(x => x.Location));
    

    现在查询:

    var point = GeoJson.Point(GeoJson.Geographic(-96.770401, 32.816774)); //long, lat
    
    var locationClause = Query<Foo>.Near(y=> y.Location, point, 20); //20 is max distance from your question. note that it's in meters
    IQueryable<Foo> query = collection.AsQueryable().Where( x=> locationClause.Inject()); 
    
    //or with the non-generic Query:  
    IQueryable<Foo> query = collection.AsQueryable().Where( x=> Query.Near("Location", point, 20).Inject());
    

    【讨论】:

    • Query的命名空间是什么?
    • 我已经尝试过这段代码,但是在 Inject() 方法上出现错误,比如缺少程序集我该如何解决这个问题,我在谷歌上搜索但没有找到命名空间
    • 上述查询已解决,但运行代码时出现错误:“LinqToMongo.Inject 方法仅适用于 LINQ Where 子句”
    • @Singh 命名空间是 MongoDB.Driver.Linq
    • 我完成查询 Mongo 2.8 的方式: var point = GeoJson.Point(GeoJson.Geographic(-96.770401, 32.816774)); var locationQuery = new FilterDefinitionBuilder().Near(tag => tag.Location, point, 20); var c = collection.Find(locationQuery).ToList();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 2015-09-01
    • 2018-07-26
    • 2012-06-06
    • 1970-01-01
    • 2016-10-13
    相关资源
    最近更新 更多