You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中编写MongoDB的$near地理位置查询语句

Node.js环境下MongoDB $near查询实现方案

前置要求

  • 存储坐标的字段必须提前创建2dsphere地理空间索引,否则无法执行$near查询,建索引示例如下:
// 原生MongoDB Node.js驱动建索引
await db.collection('places').createIndex({ location: "2dsphere" })

// Mongoose Schema中配置索引
const mongoose = require('mongoose')
const placeSchema = new mongoose.Schema({
  location: {
    type: { type: String, enum: ['Point'], required: true },
    coordinates: { type: [Number], required: true }
  }
})
placeSchema.index({ location: '2dsphere' })
const Place = mongoose.model('Place', placeSchema)

原生Node.js驱动查询示例

const { MongoClient } = require('mongodb')

async function runNearQuery() {
  const client = new MongoClient('你的MongoDB数据库连接地址')
  try {
    await client.connect()
    const db = client.db('你的数据库名称')
    const placesCol = db.collection('places')

    // 核心$near查询逻辑
    const result = await placesCol.find({
      location: {
        $near: {
          $geometry: {
            type: "Point",
            // 坐标顺序为 [经度, 纬度],请勿写反
            coordinates: [ -73.9667, 40.78 ]
          },
          // 返回距离目标点1000米以上、5000米以内的点位
          $minDistance: 1000,
          $maxDistance: 5000
        }
      }
    }).toArray()

    return result
  } finally {
    await client.close()
  }
}

Mongoose框架查询示例

const Place = require('./models/place') // 导入你定义的Place模型

async function runMongooseNearQuery() {
  const result = await Place.find({
    location: {
      $near: {
        $geometry: {
          type: "Point",
          coordinates: [ -73.9667, 40.78 ]
        },
        $minDistance: 1000,
        $maxDistance: 5000
      }
    }
  })
  return result
}

注意事项

  • 坐标填写顺序必须是*[经度, 纬度]*,顺序错误会导致查询结果完全不符合预期
  • $minDistance、$maxDistance单位均为米,可按需省略任意参数
  • $near查询默认会按距离由近到远自动排序结果,无需额外配置sort规则

内容的提问来源于stack exchange,提问作者sanjani kumar Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:06:00