2012-01-17 57 views
0

好吧我使用蒙戈db和有我的页面上的重复区域:蒙戈 - 排序while循环

try { 

    $connection = new Mongo(); 
    $database = $connection->selectDB($selectDB); 
    $collection = $database->selectCollection($selectCollection); 

} catch(MongoConnectionException $e) { 
    die("Failed to connect to database ".$e->getMessage()); 
} 

$cursor = $collection->find(); 

while ($cursor->hasNext()): $document = $cursor->getNext(); 


         echo $document['fieldName']."<br/>"; 
         echo $document['fieldType']."<br/>"; 
         echo $document['fieldLength']."<br/>"; 
         echo $document['user_id']."<br/>"; 
         echo $document['order']."<br/>"; 
         echo "<hr/>"; 

endwhile; 

这工作得很好,但我试图尽现由user_id是排序。我试过这个:

try { 

    $connection = new Mongo(); 
    $database = $connection->selectDB($selectDB); 
    $collection = $database->selectCollection($selectCollection); 

} catch(MongoConnectionException $e) { 
    die("Failed to connect to database ".$e->getMessage()); 
} 

$cursor = $collection->find().sort({user_id: -1}); 

while ($cursor->hasNext()): $document = $cursor->getNext(); 


         echo $document['fieldName']."<br/>"; 
         echo $document['fieldType']."<br/>"; 
         echo $document['fieldLength']."<br/>"; 
         echo $document['user_id']."<br/>"; 
         echo $document['order']."<br/>"; 
         echo "<hr/>"; 

endwhile; 

我修改的这行是:$ cursor = $ collection-> find()。sort({user_id:-1});

我收到的PHP错误时,ID O此。有人能告诉我合适的syntex来获得这个数组的排序。

我也曾尝试:

$cursor = $collection->find()->sort({user_id: -1}); 

and 

$cursor = $collection->find(); 
$cursor = $cursor.sort({user_id: -1}); 

任何帮助,将不胜感激。谢谢。

答案发现 *

$cursor = $collection->find(); 
$cursor->sort(array('user_id' => 1)); 
+0

对不起,我想我会开始依赖SOF有点太多,并得到一个小后感到高兴。经过约2分钟的搜索后,我找到了答案。我把它贴在我原来的帖子底部。 – user982853 2012-01-17 22:45:32

回答

5

我认为这是一个PHP语法错误:

$collection->find().sort({user_id: -1}) 

是无效的PHP。在PHP中,点运算符(“.”)用于连接字符串,而不是访问对象成员。为此,请使用箭头符号(“->”)。此外,“{user_id: -1}”对于PHP中的关联数组不正确。为此,请使用“array("user_id" => -1)”。

这给我们:

$collection->find()->sort(array("user_id" => -1)) 

我认为应该工作。