Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mongodb

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....

like image 802
hao Avatar asked Jan 31 '15 03:01

hao


2 Answers

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

like image 101
Haris Avatar answered Oct 31 '22 12:10

Haris


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.

like image 22
DaveStSomeWhere Avatar answered Oct 31 '22 12:10

DaveStSomeWhere