2010-10-03 71 views
14

是否有一種方法可以在mongo查詢中對子文檔進行排序?示例(博客集合):在MongoDB中對子文檔排序

{ 
    "_id" : ObjectId("4c69d19532f73ad544000001"), 
    "content" : "blah blah blah", 
     "comments" : { 
{"author": "jim", "content":"comment content 1", "date" : "07-24-1995"}, 
{"author": "joe", "content":"comment content 2", "date" : "07-24-1996"} 
{"author": "amy", "content":"comment content 3", "date" : "09-10-1999"} 
     } 
} 
{ 
    "_id" : ObjectId("4c69d19532f73ad544000002"), 
    "content" : "blah blah blah", 
     "comments" : { 
{"author": "jim", "content":"comment content 1", "date" : "07-24-1995"}, 
{"author": "joe", "content":"comment content 2", "date" : "07-24-1996"} 
{"author": "amy", "content":"comment content 3", "date" : "07-24-1997"} 
     } 
} 

我想在這樣但我決定命令我的博客文章,然後讓我的博客文章內有序意見通過相反的順序按日期或任何其他排序我想要的。這可能與mongoDB?

回答

0

我不認爲你可以。我在forums上提出了同樣的問題。

1

這是不可能直接從MongoDB中取出的,但是當你拉取文檔時,你可以使用你的語言的任何本地排序方法對數組進行排序,就好像它是一個對象數組一樣。這就是我在MongoDB的博客上發表評論的方式。

PHP代碼

/* 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; 
} 
4

在以上蒙戈2.4版本,可以同時更新使用$排序。 新的修改器可讓您對子文檔進行排序。

更多信息,可以閱讀此頁, http://docs.mongodb.org/manual/reference/operator/sort/

+0

但是$排序修飾符似乎對付$推,例如如果我想通過做$ INC時票數排序它,它似乎是不可能的 – Yarco 2015-12-10 09:05:07