为 2d 索引定义位置范围
您可以定义2d 索引中包含的坐标范围。 默认情况下,2d 索引的经度和纬度边界为:
大于或等于
-180
小于
180
要更改 2d 索引的位置范围,请在创建索引时指定min
和max
选项:
db.<collection>.createIndex( { <location field>: "2d" }, { min: <lower bound>, max: <upper bound> } )
min
和max
边界包含在内,并适用于经度和纬度。
关于此任务
重要
2d 索引的默认位置边界允许小于 -90 和大于 90 的纬度,这些都是无效值。 未定义使用这些无效点进行地理空间查询的行为。
为 2d 索引定义较小的位置范围可减少索引中存储的数据量,并可提高查询性能。
如果collection包含位置范围之外的坐标数据,则无法创建 2d 索引。
创建 2d 索引后,无法插入包含索引位置范围之外的坐标数据的文档。
开始之前
创建 contacts
集合:
db.contacts.insertMany( [ { name: "Evander Otylia", phone: "202-555-0193", address: [ 55.5, 42.3 ] }, { name: "Georgine Lestaw", phone: "714-555-0107", address: [ -74, 44.74 ] } ] )
address
字段包含传统坐标对。
步骤
在address
字段上创建 2d 索引。 Specify the following location bounds:
min
的边界-75
max
的边界60
db.contacts.createIndex( { address: "2d" }, { min: -75, max: 60 } )
结果
与默认的 2d 索引相比,该索引覆盖的位置范围更小,性能更高。
创建索引后,无法插入包含索引位置范围之外的坐标数据的文档。 例如,您无法插入以下文档:
db.contacts.insertOne( { name: "Paige Polson", phone: "402-555-0190", address: [ 70, 42.3 ] } )
address
字段的经度值为70
,高于60
的max
边界。
后续步骤
您可以使用 2d 索引对位置数据执行计算,例如邻近查询。