首页 > 解决方案 > 带有距离的Mongodb过滤器不起作用

问题描述

我正在尝试过滤最大距离为 10 公里的经纬度。这是我的nodejs mongodb代码实现:

  dbo.collection('CT').createIndex( { "loc" : "2dsphere" } );

     var findquery = {
       "GeoJSON.loc": {
         $near: {
           $geometry: {
              type: "Point" ,
              coordinates: [ 103.819839, 1.352083], //Long Lat
              $maxDistance:10000 
           }
         }
       }
    };


  dbo.collection("CT").find(findquery).toArray(function(err, result) {
    console.log(result);
    db.close();
  });

数据存储如下 mongodb:

[   {
    "_id": "5bc04226df7ea7503c7d57f1",
    "results": [
      {
        "ID": "FD02328677"
      }
    ],
    "GeoJSON": [
      {
        "city": "Los Angeles",
        "loc": {
          "type": "Point",
          "coordinates": [
            -118.24532,
            34.05349
          ]
        }
      },
      {
        "city": "Tampa",
        "loc": {
          "type": "Point",
          "coordinates": [
            -82.45927,
            27.94653
          ]
        }
      },
      {
        "city": "Seattle",
        "loc": {
          "type": "Point",
          "coordinates": [
            -122.32945,
            47.60358
          ]
        }
      }          
    ]   } ]

当我运行代码时,我可以获得结果(我不应该这样做),看起来过滤器功能不适用于我的代码。有什么建议吗?

标签: node.jsmongodbmongoosemongoose-schema

解决方案


只是几个错别字:

指数

 dbo.collection('CT').createIndex( { "loc" : "2dsphere" } );

应该

 dbo.collection('CT').createIndex( { "GeoJSON.loc" : "2dsphere" } );

否则,运行查询时会出错。

查询

 var findquery = {
   "GeoJSON.loc": {
     $near: {
       $geometry: {
          type: "Point" ,
          coordinates: [ 103.819839, 1.352083], //Long Lat
          $maxDistance:10000 
       }
     }
   }
};

应该

 var findquery = {
   "GeoJSON.loc": {
     $near: {
       $geometry: {
          type: "Point" ,
          coordinates: [ 103.819839, 1.352083], //Long Lat
       },
       $maxDistance:10000 
     }
   }
};

在您的查询中,$maxDistance内部$geometry被忽略。没有$maxDistancein$near所以返回所有记录。


推荐阅读