Acording to the mongoDB documentation (link) if you want to store geospatial information in a document field, you have two options, an array or an embedded document, and the order should be always longitude, latitude.
If I want to use an embedded document, how can I ensure the field's order?
Or must the fields in the embedded document have a specific name?
MongoDB documentation said the following:
A field named coordinates that specifies the object’s coordinates. If specifying latitude and longitude coordinates, list the longitude first and then latitude:
Valid longitude values are between -180 and 180, both inclusive. Valid latitude values are between -90 and 90 (both inclusive).
Oficial MongoDB documentation: https://docs.mongodb.com/manual/geospatial-queries/#geospatial-indexes
with an embedded document, regardless of the name of the field in the embedded document, the first field should contain the longitude value and the second field should contain the latitude value. For example:
Here the x field would be the longitude; and the y field would be the latitude.
Regards
2D Geospatial Index, Store Location Data
"All documents must store location data in the same order. If you use latitude and longitude as your coordinate system, always store longitude first. MongoDB’s 2d spherical index operators only recognize [ longitude, latitude] ordering."
Here's a good post about Geospatial Queries in MongoDB in case you need it.
I would advise you to name your field:
x and y
, instead oflongitude/latitude
, because after an update, longitude and latitude will be reordered in an alphabetical way, so inverted.Geospatial indexes allow us to find things based on geographic location.
We've 2 options:
In 2-D, we've a cartesian plane with
x
&y
coordinates and a bunch of different objects.The document needs to store some sort of
x
,y
location withensureIndex({'location':'2d', 'type':1})
.The
type
(optional) option specifies the direction of the index i.e. ascending or descending. It can be a compound index.Example usage:
To find nearby locations use command:
In practice, the way this is often used is through a
limit
. To limit the results to for example 20 append.limit(20)
.