在MongoDB中为球形查询创建2dsphere地理空间索引

发布于

MongoDB提供了以下支持地理空间查询的地理空间索引类型。

  • 二维索引支持在二维平面上计算几何图形的查询。
  • 2dsphere索引支持在类地球体上计算几何的查询。

在本文中,我将创建一个索引。2dsphere

示例集合

假设我们有一个包含以下文档的集合:bars

{ “_id” : 1, “name” : “Boardwalk Social”, “location” : { “type” : “Point”, “coordinates” : [ 145.77675259719823, -16.919297718553366 ] } } { “_id” : 2, “name” : “The Downunder Bar”, “location” : { “type” : “Point”, “coordinates” : [ 145.77621640842125, -16.92107838010542 ] } } { “_id” : 3, “name” : “Riley”, “location” : { “type” : “Point”, “coordinates” : [ 145.7739955395154, -16.916028253292883 ] } } { “_id” : 4, “name” : “Salt House”, “location” : { “type” : “Point”, “coordinates” : [ 145.78148426655065, -16.91823513430776 ] } } { “_id” : 5, “name” : “Rattle n Hum”, “location” : { “type” : “Point”, “coordinates” : [ 145.77746095331537, -16.920051942529685 ] } }

每个文档都有存储为 GeoJSON 对象的位置信息。

GeoJSON 对象具有一个名为指定 GeoJSON 对象类型的字段和一个名为指定对象坐标的字段。type``coordinates

创建 2dsphere 索引

现在让我们创建索引。2dsphere

db.bars.createIndex( { location : "2dsphere" } )

输出:

{ “createdCollectionAutomatically” : false, “numIndexesBefore” : 1, “numIndexesAfter” : 2, “ok” : 1 }

The index has now been created.2dsphere

现在,我们可以使用该方法检查我们的索引:[getIndexes()](https://database.guide/get-a-list-of-indexes-in-mongodb/ "Get a List of Indexes in MongoDB")

db.bars.getIndexes()

结果:

[ { “v” : 2, “key” : { “_id” : 1 }, “name” : “id” }, { “v” : 2, “key” : { “location” : “2dsphere” }, “name” : “location_2dsphere”, “2dsphereIndexVersion” : 3 } ]

我们可以看到索引是作为索引创建的,使用 ,这是我当前 MongoDB 安装(4.4)的默认版本。2dsphere``2dsphereIndexVersion``3

创建复合 2dsphere 索引

可以在与非地理空间索引键组合的复合索引中包含索引键。2dsphere

例如,我们可以将字段与字段组合以创建复合索引。location``name

让我们删除索引并创建一个复合索引:

db.bars.dropIndex("location_2dsphere")
db.bars.createIndex( { location : "2dsphere", name : 1 } )

输出:

{ “createdCollectionAutomatically” : false, “numIndexesBefore” : 1, “numIndexesAfter” : 2, “ok” : 1 }

并检查索引:

db.bars.getIndexes()

结果:

[ { “v” : 2, “key” : { “_id” : 1 }, “name” : “id” }, { “v” : 2, “key” : { “location” : “2dsphere”, “name” : 1 }, “name” : “location_2dsphere_name_1”, “2dsphereIndexVersion” : 3 } ]

复合索引可以引用多个位置和非位置字段。这与复合索引形成鲜明对比,复合索引仅限于引用一个位置字段和一个另一个字段。2dsphere``2d

更改 2dsphereIndexVersion

您可以通过在创建索引时将其添加为具有所需值的字段来更改。2dsphereIndexVersion

例:

db.bars.createIndex( 
    { location : "2dsphere" },
    { "2dsphereIndexVersion" : 2 }
)

输出:

{ “createdCollectionAutomatically” : false, “numIndexesBefore” : 1, “numIndexesAfter” : 2, “ok” : 1 }

检查索引:

db.bars.getIndexes()

结果:

[ { “v” : 2, “key” : { “_id” : 1 }, “name” : “id” }, { “v” : 2, “key” : { “location” : “2dsphere” }, “name” : “location_2dsphere”, “2dsphereIndexVersion” : 2 } ]

此索引已创建为索引版本 2。2dsphere

版本 2 是在 MongoDB 2.6 和 3.0 系列中创建的索引的默认版本。2dsphere

版本 3 是在 MongoDB 3.2 及更高版本中创建的索引的默认版本(在撰写本文时)。2dsphere

当我在没有指定字段的情况下创建索引时,它使用版本 3 创建了索引,因为这是我的 MongoDB 版本 (4.4) 的默认版本。2dsphereIndexVersion