How to perform Geospatial Queries by Using MongoDB with C#

2014/8/21 min read
bookmark this
Responsive image

1. Mongo Collection class

Define your C# model as collection.

 public class LocationModel
    {
        public MongoDB.Bson.ObjectId Id { get; set; }
        public string YouLocationBasedData { get; set; }
        public GeoJsonPoint Location { get; set; }
    }

2. Example of Saving location data to MongoDB

Before you retrieve your location from MongoDB, you need to store to the database.

Following is example of saving the data.

Location location = new Location();
                location.Location = new GeoJsonPoint(
                    new GeoJson2DGeographicCoordinates(lng, lat));

MethodOfAddDataToYourMongoDB(location); 

3. Retrieve location data based on Lng and Lat

var collection = MongoDatabase.GetCollection("Location");
            collection.CreateIndex(IndexKeys.GeoSpatialSpherical(x => x.Location));

GeoNearArgs args = new GeoNearArgs();
            args.Limit = 1;
            args.Spherical = true;
            //args.MaxDistance = 1;
            args.Near = new GeoNearPoint.Legacy(new XYPoint(yourRequest.Longitude, yourRequest.Latitude));

GeoNearResult result = collection.GeoNearAs(args);
var localResult = result.Hits.Select(x =>
            {
                return new
                {
                    SomeData= x.Document.YouLocationBasedData,
                };
            });

http://stackoverflow.com/questions/14398308/c-sharp-mongodb-near-query

need mongocsharpdriver1.9.1 higher