How to store geospatial information in mongoDB

2019-03-08 19:36发布

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?

5条回答
萌系小妹纸
2楼-- · 2019-03-08 19:51

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

查看更多
地球回转人心会变
3楼-- · 2019-03-08 19:54

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

查看更多
等我变得足够好
4楼-- · 2019-03-08 19:54

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.

查看更多
再贱就再见
5楼-- · 2019-03-08 20:05

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.

查看更多
等我变得足够好
6楼-- · 2019-03-08 20:09

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)
查看更多
登录 后发表回答