$ mongo附近,每个文档中包含一系列位置

时间:2016-12-16 18:57:44

标签: javascript node.js mongodb mongoose

我希望通过使用mongodb中的$ near运算符来接近区域内的用户,我不确定这样做的正确方法。

在我的路线中,我有一个JavaScript模型(mongoose)查找邻近的本地用户:

collection.find({
  $elemMatch: {
    locations: {
      $near: coords,
      $maxDistance: maxDistance
    }
  }
})

架构设计:

first_name: String,
  last_name: String,
  locations: [
    {
      suburb: String,
      state: String,
      postcode: String,
      longitude: Number,
      latitude: Number
    }
  ]

每个用户都有许多位置,每个位置都有纬度和经度。我尝试了$ elemMatch但没有成功,我不确定是否需要聚合或使用不同的运算符。

1 个答案:

答案 0 :(得分:0)

我建议使用GeoJSON Point格式存储坐标,然后使用mongodb 2dsphere索引。

https://docs.mongodb.com/manual/core/2dsphere/

然后,您将能够将geoNear与maxDistance和minDistance一起使用。这非常有用。

所以我的建议是你将模式修改为:

first_name: String,
  last_name: String,
  locations: [
    {
      suburb: String,
      state: String,
      postcode: String,
      geometry: {
         type: "Point",
         coordinates: [ Number, Number ]
      }
    }
  ]

(几何体为GeoJSON点格式)