José Luis
José Luis

Reputation: 3933

How to store geospatial information in mongoDB

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?

Upvotes: 32

Views: 45491

Answers (5)

Xameer
Xameer

Reputation: 31237

Geospatial indexes allow us to find things based on geographic location.

We've 2 options:

  • 2D
  • 3D

In 2-D, we've a cartesian plane with x & y coordinates and a bunch of different objects.


2D cartesian plane


The document needs to store some sort of x,y location with ensureIndex({'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:

db.collectionName.find({location: {$near:[x,y]}})

In practice, the way this is often used is through a limit. To limit the results to for example 20 append .limit(20).

db.collectionName.find({location: {$near:[x,y]}}).limit(20)

Upvotes: 3

emilie zawadzki
emilie zawadzki

Reputation: 2127

I would advise you to name your field: x and y, instead of longitude/latitude, because after an update, longitude and latitude will be reordered in an alphabetical way, so inverted.

Upvotes: 10

Isaac Peraza Leon
Isaac Peraza Leon

Reputation: 61

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

Upvotes: 4

Kay
Kay

Reputation: 3012

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:

 db.zips2.insert( { _id: 1, city: "b", loc: { x: -73.974, y: 40.764 } } )
 db.zips2.insert( { _id: 2, city: "b", loc: { x: -73.981, y: 40.768 } } )

Here the x field would be the longitude; and the y field would be the latitude.

Regards

Upvotes: 36

Andy Refuerzo
Andy Refuerzo

Reputation: 3332

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.

Upvotes: 33

Related Questions