du521521521 2012-01-17 22:38
浏览 59
已采纳

Mongo - 排序循环

Ok i am using mongo db and have a repeating region on my page:

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;

this works fine but what i am trying to do now is sort by user_id. I have tried this:

 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;

The line i altered is the: $cursor = $collection->find().sort({user_id: -1});

i am getting php error when id o this. Can someone show me the proper syntex to get this array to sort.

I have also tried:

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

and 

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

Any help would be appreciated. thanks.

answer found*

$cursor = $collection->find();
$cursor->sort(array('user_id' => 1));
  • 写回答

1条回答 默认 最新

  • dongrang2186 2012-01-17 22:52
    关注

    I think this is a PHP syntax error:

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

    is invalid PHP. In PHP, the dot operator (".") is used to concatenate strings, not to access object members. For that, use the arrow operator ("->"). Additionally, "{user_id: -1}" is not correct syntax for an associative array in PHP. For that, use "array("user_id" => -1)".

    This gives us:

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

    which I believe should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable