简体   繁体   中英

Sort data from mongodb by decending order

I am trying to output users chat history and then put it into a JSON object I want the messages to come out in descending order but when I try $cursor->sort() is throwing Call to a member function sort() on a non-object

$cursor = $collection->findOne(array('chatbetween' => $channel_name));
$cursor->sort(array('messages' => -1));
$messages = array();

for($i=0; $i<count($cursor['messages']); $i++){
    $object = array('message'=>$cursor['messages'][$i]['message'],
                    'time'=>date('Y-m-d\TH:i:s\Z', $cursor['messages'][$i]['time']->sec),
                    'user'=>$cursor['messages'][$i]['user']);

    $messages[] = $object;
}
echo json_encode($messages);

Here is what a collection looks like.

"_id": ObjectId("4f3c19e37edae1723d000000"),
   "chatbetween": "private-4f3bb96d7edae1850b0000004f3c0d2d7edae1e935010000",
   "messages"▼: {
      "0": {
       "user": "4f3c0d2d7edae1e935010000",
       "time": ISODate("2012-02-15T20: 47: 30.175Z"),
       "message": "message1"
     },
      "1": {
      "user": "4f3bb96d7edae1850b000000",
      "time": ISODate("2012-02-15T20: 47: 37.79Z"),
      "message": "message2"
    },
      "2": {
      "user": "4f3c0d2d7edae1e935010000",
      "time": ISODate("2012-02-15T20: 47: 43.295Z"),
      "message": "message3"
   }
}

Your problem is you're trying to sort sub-documents, whereas the .sort() function is for sorting documents.

So, each object in the collection is a document--in this case, each chat is a document. You can sort your chats with .sort(), but you have subdocuments called messages within your documents (sub-documents), and Mongo doesn't sort those for you.

See some answers to a similar question here: Sort Sub Documents in MongoDB

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