Mongodb(猫鼬),带有来自文档的动态位置

时间:2018-09-09 16:12:34

标签: mongodb mongoose mongodb-query aggregation-framework geospatial

我正在使用猫鼬,并有一个具有位置和最大距离的用户列表:

const userSchema = new mongoose.Schema({
  maxDistance: { type: Number, default: 1000 },
  location: {
    type: {
      type: String,
      enum: ['Point'],
      required: true,
    },
    coordinates: {
      type: [Number],
      required: true,
    },
  },
});

我想做的是让所有用户接近一个我只知道_id的用户。 虽然我知道我可以使用javascript轻松做到这一点,但我想知道Mongo在单个请求中是否有可能。

我找到了类似this的答案:

db.collection.aggregate([
    { "$geoNear": {
        "near": {
            "type": "Point",
            // those are raw values, i'd like to get coordinates of a user i'd find by _id
            "coordinates": [ 23.027573, 72.50675800000001 ],
        },
        "distanceField": "distance"
    }},

    { "$redact": {
        "$cond": {
            "if": { "$lte": [ "$distance", "$radius" ] },
            "then": "$$KEEP",
            "else": "$$PRUNE"
        }
    }}
])

我想做的是

  1. 通过其 _id
  2. 查询当前用户
  3. 以某种方式保存其位置
  4. 获取与该位置的距离小于其自己的 maxDistance 字段
  5. 的所有用户

如果可能的话,在一个查询中,我想避免做两个事情,首先是findById,然后是上一个聚合。

有可能这样做吗?

0 个答案:

没有答案