2013-05-14 102 views
2

我是mongodb的新手,试图使用地理空间从mongodb中获取结果。 有了这个[http://jamesroberts.name/blog/2012/03/12/mongodb-geospatial-query-example-in-php-with-distance-radius-in-miles-and-km/][1]参考,我创建了我的收藏2d索引器。MongoDB地理空间查询结果没有按距离顺序

我得到的结果,但没有获得排序的距离。 我也尝试过$运算符,但它返回100个文档。我想给定的位置在给定的里程附近的所有结果 任何人都可以请帮我按照排序的距离获取数据吗?

$connection = new MongoClient("mongodb://192.168.1.167"); 
$dbname="mydb"; 
$collectionName="user"; 
$db = $connection->$dbname; 
$collection = $db->$collectionName; 

$lat="36.23304900"; 
$lon="-115.24228800"; 
$radius = 40; 
$collection = $db->$collectionName; 
$radiusOfEarth = 3956; //avg radius of earth in miles 
$query = array('lnglat' =>array('$geoWithin' =>array('$centerSphere' =>array(array(floatval($lon), floatval($lat)), $radius/$radiusOfEarth))) ,'user_id' => "1234" ,'type'=>"my_type"); 

$cursor = $collection->find($query); 

回答

0

试试这个:

$cursor = $collection->find($query); 

$cursor->sort(array('distance' => -1)); 
+0

感谢奎托斯。我也试过这个。它也不起作用。因为在结果集中我没有获得距离。 – 2013-05-17 05:20:08

+0

对不起,我犯了错误。我忘记了只有在使用geoNear时才会返回“距离”。为什么不只是得到结果集,然后再自己排序呢? – kratos 2013-05-20 15:23:27

+0

$ geoWithin运算符不返回排序结果。因此,MongoDB可以比地理空间$ near或$ nearSphere查询更快地返回$ geoWithin查询,从而对结果进行排序。因此,简单地使用$ near或$ nearSphere,这样如果您不想使用上述方法,您可以获得排序结果。 – kratos 2013-05-20 15:24:57