$geoNear - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$geoNear

$geoNear聚合阶段按接近指定点的顺序返回文档。它计算与该点的距离,并将该距离包括在输出文档中。

参数

  • near:计算距离的起点,指定为 geoJSON 或传统坐标。

  • distanceField:用于存储计算距离的字段名称。

  • spherical: 表示是否使用球面几何图形的布尔值(GeoJSON 点是必需的)。

  • maxDistance: 可选。距离中心点的最大距离。

  • minDistance: 可选。距离中心点的最小距离。

  • query: 可选。要应用的其他筛选条件。

  • limit: 可选。要返回的最大文档数。

  • key: 可选。存在多个地理空间索引时用于地理空间查询的字段。

示例(MongoDB 外壳)

以下示例演示如何使用$geoNear舞台查找离给定位置最近的门店。

创建示例文档

db.stores.createIndex({ location: "2dsphere" }); db.stores.insertMany([ { _id: 1, name: "Store A", location: { type: "Point", coordinates: [-122.4, 37.8] } }, { _id: 2, name: "Store B", location: { type: "Point", coordinates: [-122.5, 37.7] } }, { _id: 3, name: "Store C", location: { type: "Point", coordinates: [-122.3, 37.9] } } ]);

查询示例

db.stores.aggregate([ { $geoNear: { near: { type: "Point", coordinates: [-122.4, 37.8] }, distanceField: "distance", spherical: true } } ]);

输出

[ { _id: 1, name: 'Store A', location: { type: 'Point', coordinates: [ -122.4, 37.8 ] }, distance: 0 }, { _id: 3, name: 'Store C', location: { type: 'Point', coordinates: [ -122.3, 37.9 ] }, distance: 13877.82 }, { _id: 2, name: 'Store B', location: { type: 'Point', coordinates: [ -122.5, 37.7 ] }, distance: 15557.89 } ]

代码示例

要查看使用$geoNear聚合阶段的代码示例,请选择要使用的语言对应的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('stores'); const result = await collection.aggregate([ { $geoNear: { near: { type: "Point", coordinates: [-122.4, 37.8] }, distanceField: "distance", spherical: true } } ]).toArray(); console.log(result); await client.close(); } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['stores'] result = list(collection.aggregate([ { '$geoNear': { 'near': { 'type': 'Point', 'coordinates': [-122.4, 37.8] }, 'distanceField': 'distance', 'spherical': True } } ])) print(result) client.close() example()