MongoDB - GeoJSON - 查找半径内的文档

MongoDB - GeoJSON - Find document inside a radius

感谢之前的计算,我得到了之前查询的城镇中心的坐标:[lon, lat]。我在查询 radius 中有另一个参数。我想在这个虚拟 cercle 中找到我的数据库中的所有文档。

我的架构:

const artisanSchema = new Schema ({
  created: { type: Date, default: Date.now },
  updated: { type: Date, default: Date.now },
  name: { type: String, index: true },
  address: {
    street: String,
    zip: { type: String, index: true },
    town: { type: String, index: true }
  },
  contact: {
    tel: String,
    mail: String,
    web: String
  },
  activities: [String],
  type: String,
  geometry: mongoose.Schema.Types.Point, //"geometry": {"coordinates":[0.704378,45.194518],"type": "Point"
}
  tagMetier: [Number]
});

我尝试这样的查询:

Artisan.
  find ({
    'tagMetier': tag,
    'geometry': { $geoWithin: { $centerSphere: [ [ myTown.longitude, myTown.latitude ], rad ] } }
  },
  function (err, artisan) {
    if (err) throw err;
    else {
      res.send(artisan);
    }
  })
  .limit(10)

如果我以半径 5 公里的城镇为目标,我得到的答案是距我居住地 200 公里或更远的城镇。

首先创建索引

您可以确保 moongose schema level 上的索引或直接 Mongodb Collection

在 Mongo 数据库中这样

db.Artisan.createIndex( { geometry : "2dsphere" } )

或在月色图式层次

 geometry: mongoose.Schema.Types.Point, index: "2dsphere"

现在查询

  Artisan.find({ location:
   { $geoWithin:
      { $centerSphere: [ [ myTown.longitude, myTown.latitude ], 5 / 3963.2 ] } } ,'tagMetier': tag})

假设你的半径是弧度
以下将找到五英里范围内的所有 Artisan

您可以使用 $maxDistance 视为 meter

var METERS_PER_MILE = 1609.34
Artisan.find({ location: { $nearSphere: { $geometry: { type: "Point", coordinates: [ myTown.longitude, myTown.latitude ] }, $maxDistance: rad * METERS_PER_MILE } } })

有关更多信息,请检查此 https://docs.mongodb.com/manual/tutorial/geospatial-tutorial/

傻我,

rad不是公制单位如千米,而是弧度单位,因为地球是一个不完美的球体(所以我们简化成一个大球来计算)。

如果我想要以公里为单位的结果,我必须这样做:rad/6378.1 以英里为单位:rad/3963.2

所以最后我写了:geometry': { $geoWithin: { $centerSphere: [ [ myTown.longitude, myTown.latitude ], rad/6378.1 ] } }

瞧。