Is there a way to sort sub documents in a mongo query?
For example:
{
\"_id\" : ObjectId(\"4c69d19532f73ad544000001\"),
\"content\" : \"blah bla
It's not possible directly out of MongoDB, however when you pull the document you can then sort the array as if it was an array of objects, using whatever native sort method your language has. This is how I do comments on my blog with MongoDB.
PHP Code
/* Takes an array of comments and turns them into native objects */
public static function loadMany($pcomments)
{
$comments = array();
if(isset($pcomments) && count($pcomments) > 0)
{
foreach($pcomments as $key => $comment)
{
$comment['data']['index'] = $key;
$comments[] = Comment::loadOne($comment['data']);
}
}
usort($comments, "comment_compare");
return $comments;
}
/* Compares comment timestamps */
function comment_compare($a, $b)
{
if($a->timestamp->sec == $b->timestamp->sec)
{
return 0;
}
return ($a->timestamp->sec < $b->timestamp->sec) ? -1 : 1;
}