从 MongoDB 2.4 开始,存储和索引 GeoJSON。你可以在这里找到所有的概念。
如何在 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());