如何在圆形对象半径内找到 $near

How to to find $near within a circle object radius

我很难用文档中的字段为 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 但似乎没有用。 谢谢

您不能在标准查询操作中以这种方式从文档中赋值。而是在此处使用 aggregation framework 来 "project" 距查询点的距离,然后看到该距离落在文档上指定的半径范围内。

您使用$geoNear pipeline operator in order to project the distance and the $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 的遗留坐标对。