【问题标题】:MongoDB Geospatial query result not getting in order of DistanceMongoDB地理空间查询结果未按距离顺序排列
【发布时间】:2013-05-08 22:03:04
【问题描述】:

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

我得到了结果,但没有按距离排序。 我也尝试了 $near 运算符,但它返回 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);

【问题讨论】:

    标签: geospatial mongodb-php


    【解决方案1】:

    试试这个:

    $cursor = $collection->find($query);
    
    $cursor->sort(array('distance' => -1));
    

    【讨论】:

    • 谢谢克拉托斯。我也试过这个。它也不起作用。因为在结果集中我没有得到距离。
    • 对不起,我弄错了。我忘记了“距离”只有在您使用 geoNear 时才会返回。为什么不直接获取结果集,然后再自行排序?
    • $geoWithin 运算符不返回排序结果。因此,MongoDB 可以比地理空间 $near 或 $nearSphere 查询更快地返回 $geoWithin 查询,后者对结果进行排序。因此,简而言之,使用 $near 或 $nearSphere 以便在您不想使用我上面的方法时获得排序结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    相关资源
    最近更新 更多