【问题标题】:How to to find $near within a circle object radius如何在圆形对象半径内找到 $near
【发布时间】:2015-08-04 14:28:31
【问题描述】:

我很难使用文档中的字段为 mongo 查询分配值:

我的架构是

var TestSchema = new Schema({
  loc: {
    lng: {
      type: Number
    },
    lat: {
      type: Number
    }
  },
  radius: {
    type: Number
  }
});
module.exports = mongoose.model("Test", TestSchema );`

并且我想找到该字段提供的半径范围内的所有文档。

Test.find({'loc': {'$near':[0.001, 0.001] ,'$maxDistance': ???}});

我试过而不是 ??? :this.radius 但似乎不起作用。 谢谢。

【问题讨论】:

    标签: node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您不能在标准查询操作中以这种方式从文档中分配值。而是在这里使用aggregation framework 来“投影”到查询点的距离,然后查看该距离是否在文档上指定的半径范围内。

    您使用$geoNear 管道运算符来投影距离,并使用$redact 操作来删除不满足在半径范围内条件的文档:

    Test.aggregate(
        [
            { "$geoNear": {
                "near": [0.001, 0.001],
                "distanceField": "distance"
            }},
            { "$redact": {
                "$cond": {
                    "if": { "$lt": "$distance", "$radius" },
                    "then": "$$KEEP",
                    "else": "$$PRUNE"
                }
            }}
        ],
        function(err,results) {
    
        }
    ) 
    

    注意$geoNear 运算符上的选项。 “distanceField”是必需的,因为这是表示距查询点的距离的字段。其他选项(如“spherical”和“distanceMultiplier”)可能适用,具体取决于您的索引是“2sphere”还是分别使用旧版 GeoJSON 坐标对。

    【讨论】:

      猜你喜欢
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 2021-11-09
      • 2017-04-07
      • 1970-01-01
      • 2012-10-05
      相关资源
      最近更新 更多