2016-12-01 32 views
0

我有一群这样的:

{ 
      "$group": { 
       "_id": "$conversationId" 
       "conversation": { 
        "$push": {"from": { 
          "firstName": "$fromObj.firstName", 
          "lastName": "$fromObj.lastName", 
          "title": "$fromObj.title", 
          "picture": "$fromObj.picture" 

         } 
         , "to": { 
          "firstName": "$toObj.firstName", 
          "lastName": "$toObj.lastName", 
          "title": "$toObj.title", 
          "picture": "$toObj.picture" 
         } 
         , "content": "$content", 
         "_id": "$_id", 
         "conversationId": "$conversationId", 
         "unreaded": "$unreaded" 
        }} 

      } 

     } 

里面$push一部分,我需要推刚刚过去的5个项目我该怎么办呢?这将是理想的,如果可以直接将$ limit添加到$ push任何解决方案吗?

+2

你尝试在聚合管道的下一部分中启用“切片”以限制它们。请参阅https://docs.mongodb.com/manual/reference/operator/aggregation/slice/ – raj

+1

[Mongodb聚合管道如何限制组推送]可能的副本(http://stackoverflow.com/questions/24594049/mongodb -aggregation流水线知识到极限一组推) – styvane

回答

1

您可以通过添加一个$project阶段的流水线做到这一点后,使用$slice$group把刚刚从累积conversation阵列中的每个文档的最后5个元素:使用`$

{$project: {conversation: {$slice: ['$conversation', -5]}}}