Sort Sub Documents in MongoDB

后端 未结 5 1260
北恋
北恋 2020-12-17 14:52

Is there a way to sort sub documents in a mongo query?

For example:

{
  \"_id\" : ObjectId(\"4c69d19532f73ad544000001\"),
  \"content\" : \"blah bla         


        
5条回答
  •  一个人的身影
    2020-12-17 15:13

    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;
    }
    

提交回复
热议问题