hao hao - 1 year ago 110
PHP Question

how to output a collection of data from mongodb sort by date

I want to retrieve 10 rows of latest news from mongodb.
First I need to sort the data by the field 'timestamp' by ascending order. Then I need to choose the top 10 rows which are the rows with the latest timestamp.
This is how I establish my connection (successfully)

$m = new MongoClient("mongodb://");
$db = $m ->nutch;
//echo "Database nutch selected";

$collection = $db -> crawl_data;

$cursor = $collection->find();

This is how I tried to get the data following the PHP manual guide

$cursor->sort(array('timestamp' => 1));
foreach($cursor as $doc){
echo $doc["title"];

FYI: the data type of timestamp is string: "2015/01/31". I am not sure if this is the reason.

Also, When I do php with MySql, the browser always tells me at which line the problem is. With mongodb, it does not give you any error reporting except a blank page....

Answer Source

The php syntax is a bit confusing.

The Sort() and Limit() methods can be done on the find (regardless of order the sort will always happen first).

It would look something like this:

$cursor = $collection->find ()->sort(array('timestamp'=>-1))->limit(10);

And then you can reverse the order of the 10 documents in php, or you would probably need to use the aggregation framework.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download