C#MongoDB"近"查询

Ita*_*ayM 8 linq collections c#-4.0 mongodb-.net-driver

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

{
"_id": {
    "$oid": "50e9f38fbd7680c8090bcb4"
},
"guid": "D3G5wQ8RZL",
"lat": 37.503287248864,
"lng": -121.97620341421,
Run Code Online (Sandbox Code Playgroud)

我想使用C#linq预先形成"NEAR"查询

它需要看起来像那样

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

我的问题是 - 我应该对"位置"的内容进行编码?我如何查看上面收藏的积分?

谢谢.

Jon*_*der 21

从MongoDB 2.4开始,存储和索引GeoJSON.你可以在这里找到所有的概念.

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

public class Foo
{
  public GeoJsonPoint<GeoJson2DGeographicCoordinates> Location { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

示例实例:

var docToInsert = new Foo
            {   
                Location = new GeoJsonPoint<GeoJson2DGeographicCoordinates>(
                    new GeoJson2DGeographicCoordinates(-121.97620341421, 37.503287248864))
            });
Run Code Online (Sandbox Code Playgroud)

$ near需要地理空间索引,因为我们存储GeoJSON,所以它特别需要一个2dsphere索引:

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

现在查询:

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());
Run Code Online (Sandbox Code Playgroud)

  • Query 的命名空间是什么? (2认同)