2013-07-20 65 views
2

裏面我有對話的集合是這樣的:MongoDB的分類和限制數組

[ 
     { 
      title: ..., 
      members: [...], 
      messages: [ 
       { _id: ..., date: ..., text: ... }, 
       { _id: ..., date: ..., text: ... }, 
       ... 
      ] 
     }, 
     { 
      title: ..., 
      members: [...], 
      messages: [] 
     }, 
     ... 
    ] 

一些文件有一個空的消息數組。 我需要選擇幾個集合(一個用戶),但兩件事情:

1) The order of messages must be reversed (or messages must be ordered by date desc, result is the same). 
2) The number of messages for each conversation must be limited. 

我嘗試使用此查詢扭轉消息:

db.conversations.aggregate([ 
     {$match: {members: 'someUserId'}} 
     {$unwind: '$messages'}, 
     {$sort: {'messages.date': -1}}, 
     {$group: { 
      _id: '$_id', 
      title: {$first: '$title'}, 
      members: {$first: '$members'}, 
      messages: {$push: '$messages'} 
     }} 
    ]) 

但同樣有兩個問題:談話沒有消息未被選擇,消息仍然不受限制。

你有什麼想法,如何解決它?或者如何解決這個問題之一? 謝謝!

回答