Tutorial: GeoSpatial Search In MongoDB The Easy Way!
Dĵ ΝιΓΞΗΛψΚ
Posted on January 16, 2020
let's say we have a bunch of art galleries stored in mongodb located in paris and we want to retrieve only those that are within 20 kilometers of the eiffel tower.
mongodb makes it extremely easy if you store the entities properly tagged with their longitudes and latitudes.
Getting Started
if you haven't already, please see the introductory article mentioned below in order to get a new project setup before continuing with the rest of this article.
the Coordinates2D type is a special class supplied by the library to streamline the storage & retrieval of geographical data.
Create Some Entities
awaitnew[]{newArtGallery{Name="Galleria Le-Pari",Location=newCoordinates2D(48.8539241,2.2913515)},newArtGallery{Name="Versailles House Of Art",Location=newCoordinates2D(48.796964,2.137456)},newArtGallery{Name="Poissy Arts & Crafts",Location=newCoordinates2D(48.928860,2.046889)}}.SaveAsync();
we are setting the locations of these galleries by creating new instances of Coordinates2D class supplying the longitude and latitude to the constructor. finally the whole array is persisted to mongodb by calling the .SaveAsync() extension method which issues a bulk write command.
Create An Index
mongodb geospatial queries require an index to be created which can be easily done as follows:
we specify the index key as the Location property of the ArtGallery class and type of key as Geo2DSphere. also we are telling mongodb to build the index in the foreground with the .Option() method.
if the above exercise has piqued your interest enough to discover how to easily get things done with mongodb using c#, please visit the official website of MongoDB.Entities. you can also check out the source code on github:
A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management
MongoDB.Entities
A light-weight .net standard library with barely any overhead that aims to simplify access to mongodb by abstracting the official driver while adding useful features on top of it resulting in an elegant API surface which produces beautiful, human friendly data access code.
More Info:
please visit the official website for detailed documentation: