How to store geospatial information in mongoDB

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 03:40:03

问题


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?


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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.



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)



回答5:


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



来源:https://stackoverflow.com/questions/15274834/how-to-store-geospatial-information-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!