Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MongoDB "Near" Query

I have a mongo collection that look like that:

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

} I want to preform "NEAR" query using C# linq

it need to look something like that

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

MY question is - What should I code insted of "Location"? how can I check the Points from the collection above?

Thanks.

like image 230
ItayM Avatar asked Jan 18 '13 11:01

ItayM


1 Answers

As of MongoDB 2.4, store and index GeoJSON. You can find all the concepts here.

How to define a GeoJSON property on a POCO type:

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

An example instantiation:

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

$near requires a geospatial index, and since we're storing GeoJSON, it specifically requires a 2dsphere index:

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

Now the query:

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());
like image 73
Jonathan Roeder Avatar answered Sep 23 '22 06:09

Jonathan Roeder