Docs 菜单
Docs 主页
/
MongoDB Manual
/ / / /

创建 2dsphere 索引

在此页面上

  • 开始之前
  • 步骤
  • 后续步骤
  • 了解详情

2dsphere 索引支持对类似地球的球体进行地理空间查询。例如,2dsphere 索引可以:

  • 确定指定区域内的点。

  • 计算到指定点的距离。

  • 返回坐标查询的精确匹配结果。

要创建2 dsphere 索引,请使用 db.collection.createIndex()方法并指定字符串"2dsphere"作为索引类型:

db.<collection>.createIndex( { <location field> : "2dsphere" } )

<location field>中的值必须是以下任一值:

创建一个 places 集合,其中包含以下文档:

db.places.insertMany( [
{
loc: { type: "Point", coordinates: [ -73.97, 40.77 ] },
name: "Central Park",
category : "Park"
},
{
loc: { type: "Point", coordinates: [ -73.88, 40.78 ] },
name: "La Guardia Airport",
category: "Airport"
},
{
loc: { type: "Point", coordinates: [ -1.83, 51.18 ] },
name: "Stonehenge",
category : "Monument"
}
] )

loc字段中的值是GeoJSON 点。

以下操作在位置字段loc上创建2 dsphere 索引:

db.places.createIndex( { loc : "2dsphere" } )

创建2 dsphere 索引后,您可以使用该索引进行地理空间查询。 要了解更多信息,请参阅查询2 dsphere 索引。

后退

2dsphere

来年

查询