本文解释了MongoDB中的地理空间索引和查询。它使用2DSPHERE索引详细介绍了使用Geojson进行有效的基于位置的搜索。本文涵盖了地理空间操作员,例如附近,$ geowithin及其性能效益
mongoDB通过其2DSPHERE索引提供了对地理空间数据的强大支持。该索引允许有效查询存储为Geojson对象的位置数据。要使用它,您首先需要正确构建数据。通常,位置数据存储在文档中,作为类型 Geojson
的字段。 Geojson支持各种几何形状,例如 point
, polygon
, linestring
等。 'type':&quot“ point”; quot" quortinates;:[-73.9728,40.7644] //经度,latitude}}
接下来,您在 code> field <p>接下来class =“ javaScript”> db.restaurants.createindex({位置:&quot;&quot;&quot;&quot; quot; quot;})</p>
创建索引后,您可以使用地理空间操作员执行查询。 Common operators include $near
, $nearSphere
, $geoWithin
, and $geoIntersects
.
$near
and $nearSphere
: These operators find documents within a specified radius of a given point. $near
uses planar geometry, suitable for small distances, while $nearSphere
uses spherical geometry, more accurate for larger distances.$geoWithin
: This operator finds documents whose geometries are entirely within a specified geometry (eg, a circle, polygon).$geoIntersects
: This operator finds documents whose geometries intersect with a specified geometry.Here are examples of queries:
Find restaurants within 10 kilometers of a point:
<code class="“" javascript> db.restaurants.find({位置:{$ nectersphere:{$ gemetry:{type:&qoint&qoint&qoint&qoint&qoids&qoids&qoids&qoids; [-73.9728,40.7644]} polygon: <pre class="brush:php;toolbar:false"> db.restaurants.find({位置:{$ geowwithin:{$ geetry:{type:type; polygon&quord; polygon&quord; polygon; polygon; polygon; polygon; polygon; polygon; polygon; polygon; polygon; polygon; polygon; polygon; polygon; polygon&quort; ]]]]}}}})
地理空间索引极大地改善了基于位置的查询的性能。如果没有索引,MongoDB将执行集合扫描,检查集合中的每个文档以查找匹配位置。这是极低效率的,尤其是对于大型数据集。
使用2DDSPHERE索引,MongoDB可以有效利用R-Trees(例如R-Trees)等空间数据结构来快速缩小搜索空间的范围。这使其能够更快地返回结果,尤其是对于涉及接近搜索的查询(近
, $ neartsphere
)。在处理包含数百万个位置点的大型数据集时,性能增益最为明显。查询执行时间将大大减少,从而提高应用程序的响应能力。与未索引的搜索相比,差异的数量级可以更快。
是的,mongodb支持复杂的地理位置查询,包括在多边形中查找点。如上一节所示, $ geowithin
运算符与 polygon
geojson对象结合使用,允许您有效地找到其位置属于指定的多边形的文档。这对于诸如在特定城市边界内找到所有餐馆或确定定义义义区域内的所有餐厅的场景很有用。您还可以使用 $ Geointersects
操作员查找与更复杂的几何形状相交的文档,例如行或其他多边形。这种灵活性使您可以在应用程序中构建基于位置的复杂功能。
几个常见的陷阱可以阻止地球动员在Mongodb中的地球序列特征的有效实现。 Geojson对象。使用错误的数据类型将阻止索引正常工作。
通过仔细解决这些潜在问题,您可以确保在MongoDB应用程序中有效而准确的地理空间功能。
>以上是如何在MongoDB中使用地理空间索引和查询进行基于位置的应用程序?的详细内容。更多信息请关注PHP中文网其他相关文章!