near返回集合中的所有文档


near returns all documents in a collection

我有一个下面的代码,它应该返回mongodb中的lat,long,它们与我提到的那些接近。但问题是,它会返回所有的lat,long。

$collection->ensureIndex(array("location" => "2d"));
$a=array(24.8934,67.0281);
//print_r($a);
$distance='500';
$query = array('location' => array('$near' => array(24.8934,67.0281)));

$cursor = $collection->find($query);
try{
if ($cursor) {
   echo $arr= json_encode(iterator_to_array($cursor));
 // $j= json_decode($arr,false);
echo var_dump(json_decode($arr));
$j = json_decode($arr,false);
 $lat= $j->{'57237036d89c45e1e3fda94e'}->location[0]; 
 $lng= $j->{'57237036d89c45e1e3fda94e'}->location[1]; 
} else {
    echo "{ 'status' : 'false' }";
}

它返回以下内容:

object(stdClass)[7]
  public '572453d55addfab49090ea71' => 
    object(stdClass)[6]
      public '_id' => 
        object(stdClass)[8]
          public '$id' => string '572453d55addfab49090ea71' (length=24)
      public 'location' => 
        array (size=2)
          0 => float 24.8615
          1 => float 67.0099
  public '57237036d89c45e1e3fda94e' => 
    object(stdClass)[9]
      public '_id' => 
        object(stdClass)[10]
          public '$id' => string '57237036d89c45e1e3fda94e' (length=24)
      public 'location' => 
        array (size=2)
          0 => float 33.7715
          1 => float 72.7511

相反,它应该只返回第一个文档。

示例代码工作不正常的原因是定义了$distance变量,但没有将其传递给查询。

您需要将代码修改为类似于以下示例:

$distance=500;
$cursor = $collection->find(['location' =>
['$near'=> [ 24.8934,67.0281 ],
'$maxDistance' => $distance]]);

对于大多数用例,我们建议您应该使用较新的2dsphere索引,该索引使用类似地球的几何体和GeoJSON对象。有关此功能的详细信息,请查看2dsphere索引。

如果使用2dsphere索引,代码将类似于以下内容:

$distance=500;
$cursor = $collection->find(['location' =>
['$near'=>
['$geometry'=>
[ 'type' => "Point",  'coordinates' => [ 24.8934,67.0281 ] ],
'$maxDistance' => $distance]]]);

您可能还发现球形几何体教程很有帮助。