2016-04-30 56 views
0

我有一個下面的代碼應該返回那些拉特,長在mongodb這是我提到的附近。但問題是,它返回所有經緯度。附近返回集合中的所有文檔

$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 

相反,它應該只返回第一個文檔。

回答

1

示例代碼無法正常工作的原因是$ distance變量已定義,但未傳遞給查詢。

您將需要修改代碼以類似於下面的例子:

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

對於大多數使用情況,我們建議你應該使用它採用類似地球的幾何形狀和GeoJSON的較新的2dsphere指數對象。請查閱2dsphere index瞭解更多關於此功能的信息。

如果使用2dsphere指數,代碼將類似於此:

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

您也可以找到spherical geometry tutorial很有幫助。