【问题标题】:How to add some more constraints with geoNear如何使用 geoNear 添加更多约束
【发布时间】:2015-01-07 09:16:31
【问题描述】:

这是我的猫鼬模式 -

var userDestinationSchema = mongoose.Schema({

    uid: String,                
    update_time: Date,          
    some_data: String,

    location:{                  //<INDEXED as 2d>
        lon: Number,
        lat: Number
    }
});



var userDestinationModel = mongoose.model('userDestinationModel', userDestinationSchema);

要查询 geoNear 的模型,我这样做了。

userDestinationModel.geoNear(lng, lat, { maxDistance : 1.5 }, 
              function(err, results, stats) {
                   console.log(results);
                });

如何添加更多约束,例如 some_data 的特定值?

【问题讨论】:

    标签: node.js mongodb geolocation mongoose mongodb-query


    【解决方案1】:

    “最佳方式”是根据需要使用$near 运算符或$nearSphere。 mongoose 的.geoNear() 方法使用MongoDB 的旧geoNear command。在最近的版本中,其他运算符与其他查询运算符配合得更好:

    userDestinationModel.find({ 
        "location": {
            "$near": [ lng, lat ],
            "$maxDistance": 1.5
        },
        "update_time": { "$gt": new Date("2015-01-01") }
    },function(err,result) {
    
    });
    

    也可以使用$geoNear的聚合框架形式。这有它自己的“查询”选项来指定附加信息:

    userDestinationModel.aggregate(
        [
            { "$geoNear": {
                "near": [ lng, lat ],
                "maxDistance": 1.5,
                "distanceField": "distance",
                "query": {
                    "update_time": { "$gt": new Date("2015-01-01") }
                }
            }}
        ],
        function(err,result) {
    
        }
    );
    

    这允许其他选项以及类似于"command form" 的投影位置和结果中的附加“distanceField”,您可以将其用于以后的排序或过滤等。

    您还应该能够将“查询”指定为 mongoose 方法的选项:

    userDestinationModel.geoNear(lng, lat, 
        { 
            "maxDistance" : 1.5, 
            "query": { 
                "update_time": { "$gt": new Date("2015-01-01") } 
            } 
        }, 
        function(err, results, stats) {
            console.log(results);
        });
    

    但作为个人偏好,除非您依赖旧服务器版本支持,否则我会选择较新的运营商。

    同时尝试从传统的坐标对转移到 GeoJSON,因为它与您可能会在数据交换中使用的其他 API 更加一致,并且支持更广泛的 GeoJSON 类型。请注意,如果迁移到 GeoJSON,“maxDistance”等参数和返回的距离以“米”为单位,而不是“弧度”,与传统坐标的情况一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多