Mongo DB have written a great article on Geospatial Queries, this is a quick blog post summarizing that blog post, and how to quickly setup geo spatial queries in Mongo DB. Geo Spatial queries allow you to store entities that have a coordinates, like addresses etc and perform a Near query using coordinates.
public class MyPlaceWithLocationDocument
{
[BsonId]
public ObjectId Id { get; set; }
public GeoJsonPoint<GeoJson2DCoordinates>? GeoCoordinates { get; set; }
public string? POI { get; set; }
}
2. Add a index to your Mongo DB cluster, ensure that GeoCoordinates is the name of your field in your class that has the Geo coordinates.
{ "GeoCoordinates ": "2dsphere" }
3. Write your search code
private readonly IMongoCollection<T> _Collection;
public MongoDBClient(string connectionString, string DatabaseName, string collectionName)
{
var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.ConnectTimeout = TimeSpan.FromSeconds(2);
settings.ServerSelectionTimeout = TimeSpan.FromSeconds(2);
var mongoClient = new MongoClient(settings);
var mongoDatabase = mongoClient.GetDatabase(DatabaseName);
_Collection = mongoDatabase.GetCollection<T>(collectionName);
}
public async Task<IEnumerable<T>> GeoClosest(double lon, double lat, double? maxDistanceMetres, double? minDistanceMetres, Expression<Func<T, object>> comparisonField)
{
// Instantiate builder
var builder = Builders<T>.Filter;
// Set center point
var point = GeoJson.Point(GeoJson.Position(lon, lat));
// Create geospatial query
var filter = builder.Near(comparisonField, point, maxDistance: maxDistanceMetres, minDistance: minDistanceMetres);
// Execute query
return await _Collection.Find(filter).ToListAsync();
}
public IQueryable<T> Collection()
{
return _Collection.AsQueryable<T>();
}
4. When applying and using the coordinates, remember:
Longitude values are considered the x-coordinate, while latitude values are the y-coordinate.
This is 3 easy steps to setup and use Geo Spatial searching, useful if you want to show pictures that have geo tags and search them from a no-sql database.