Geographical queries with MongoDb
We will now show how to conduct a geographic query on an ontology within Onesait Platform. To do this, first, there must be firstly an ontology with a Geometry-point type field where the location is stored. For this example a such ontology called pubsOntology has been created, where the location of different bars will be stored in the location field.
To query which bar is closest to a specific location, the first step would be to indicate to MongoDb that the field where the location is being stored (in this case location) follows the GeoJSON structure. This is done by invoking the createIndex() command on the field where the location is being stored, and that has been previously defined as Geometry-point type.
The next step would be to formulate a find-type query that specifies that you want to know the point closest to a specific location. In the following image (from a viewer created from plataforma), the three pubs that are registered (pub01, pub02, pub03) are represented, and the points in a circle show where the nearest pub is to the position.
In the case of circle number one, the query would be:
db.pubsOntology.find({ 'pubsOntology.location':
{$near: {$geometry: {type: "Point",coordinates:[-1.130500,37.987087]},}}})
The result is a list of bars, ordered from closest to furthest:
Â
As expected, the nearest bar would be Pub02, followed by Pub01, and Pub03. If we now change the location of the query to point 2, the result will be different:
As you can see, in this case the closest bar would be Pub03.