Docs 菜单
Docs 主页
/ /

查询平面上某点附近的位置

您可以查询平面上指定点附近出现的位置数据。

要查询指定点附近的位置数据,请使用 $near操作符:

db.<collection>.find( {
<location field> : {
$near : [ <longitude>, <latitude> ],
$maxDistance : <distance in meters>
}
} )
  • $near操作符中指定坐标对时,请先列出经度,然后列出纬度

    • 有效经度值介于 -180180 之间,两者均包括在内。

    • 有效纬度值介于 -9090 之间,两者均包括在内。

  • $maxDistance字段中指定距离(以为单位)。

  1. 创建 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 字段包含传统坐标对

  2. 要使用$near操作符查询位置数据,您必须在包含位置数据的字段上创建地理空间索引

    address字段上创建 2d 索引:

    db.contacts.createIndex( { address: "2d" } )

使用$near来查询collection。以下$near查询返回具有address字段在坐标对[ -73.92, 40.78 ] 50 米范围内的文档:

db.contacts.find( {
address: {
$near: [ -73.92, 40.78 ],
$maxDistance : 50
}
} )

输出:

[
{
_id: ObjectId("640a3dd9c639b6f094b00e89"),
name: 'Georgine Lestaw',
phone: '714-555-0107',
address: [ -74, 44.74 ]
}
]

结果按与查询点的距离从最近到最远排序。

后退

查询

在此页面上