查询平面形状上的形状内的位置
要在平坦表面上查询指定形状内的位置数据,请使用$geoWithin
运算符。要使用$geoWithin
与出现在平坦表面上的数据,请使用以下语法
db.<collection>.find( { <location field> : { $geoWithin : { <shape operator> : <coordinates> } } } )
替换以下查询值
字段 | 描述 |
---|---|
<collection> | 要查询的集合。 |
<location field> | 包含您位置数据的字段。对于平坦表面的查询,您的数据必须以旧坐标对的形式存储。 |
<shape operator> | |
<coordinates> | 定义要查询的形状边界的坐标。当与 指定经纬度坐标时,先列出经度,然后是纬度。
|
关于此任务
$geoWithin
不需要地理空间索引。然而,地理空间索引可以提高查询性能。
开始之前
创建 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
包含 旧版坐标对。
步骤
使用 $geoWithin
查询 contacts
集合。下面的 $geoWithin
查询使用 $box
操作符返回位于指定矩形内的文档
db.contacts.find( { address: { $geoWithin: { $box: [ [ 49, 40 ], [ 60, 60 ] ] } } } )
输出
[ { _id: ObjectId("647e4e496cdaf4dc323ec92a"), name: 'Evander Otylia', phone: '202-555-0193', address: [ 55.5, 42.3 ] } ]
$box
操作符的值表示查询矩形内的左下角和右上角。
前面显示的 $geoWithin
查询返回位于这些顶点形成的矩形内的文档
[ 49, 40 ]
[ 49, 60 ]
[ 60, 60 ]
[ 60, 40 ]
了解更多
要了解如何使用 $geoWithin
操作符与其他形状一起使用,请参阅这些页面