How to perform Geospatial Queries by Using MongoDB with C#

2014/08/022 min read
bookmark this
Responsive image

Table of Contents

  1. Introduction
  2. Mongo Collection Class
  3. Saving Location Data to MongoDB
  4. Retrieving Location Data Based on Longitude and Latitude
  5. Conclusion

Introduction

This blog shows an example of how to use C# to perform location-based queries with MongoDB using geospatial indexes.

Mongo Collection Class

Define your C# model as a collection.

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

Saving Location Data to MongoDB

Before you retrieve location data from MongoDB, you need to store it in the database.

Following is an example of saving the data.

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

MethodOfAddDataToYourMongoDB(location);

Retrieving Location Data Based on Longitude and Latitude

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

Requires mongocsharpdriver 1.9.1 or higher.

Conclusion

Using MongoDB's geospatial features with C# allows you to store and query location-based data efficiently. Make sure to create a geospatial spherical index on your location field for optimal performance.