简体   繁体   中英

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://127.0.0.1");
  $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....

Sort doesn't work like this anymore, To be able to sort with find, you simply use the second find parameter like this:

$filter  = [];
$options = ['sort' => ['timestamp' => -1]];

$client = new MongoDB\Client('mongodb://localhost');
$client->mydb->mycollection->find($filter, $options);

copied from this answer

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.

You can use the _id field to sort by timestamp.

The following query can print the latest 10 records.

$cursor = $collection->find()->sort( array("_id" => -1 ))->limit(10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM