2016-11-11 45 views
2

我正在使用MongoDB的聚合管道,以我想要的形式獲取我的文檔。作爲最後一步的彙總,我使用$project將文檔放入最終形式。使用MongoDB項目數組

但我在投影和排列子文檔時遇到了麻煩。以下是我目前從aggrgation得到:

{ 
    "_id": "581c8c3df1325f68ffd23386", 
    "count": 14, 
    "authors": [ 
    { 
     "author": { 
     "author": "57f246b9e01e6c6f08e1d99a", 
     "post": "581c8c3df1325f68ffd23386" 
     }, 
     "count": 13 
    }, 
    { 
     "author": { 
     "author": "5824382511f16d0f3fd5aaf2", 
     "post": "581c8c3df1325f68ffd23386" 
     }, 
     "count": 1 
    } 
    ] 
} 

我想$projectauthors陣列,這樣的回報將是這樣的:

{ 
    "_id": "581c8c3df1325f68ffd23386", 
    "count": 14, 
    "authors": [ 
    { 
     "_id": "57f246b9e01e6c6f08e1d99a", 
     "count": 13 
    }, 
    { 
     "_id": "5824382511f16d0f3fd5aaf2", 
     "count": 1 
    } 
    ] 
} 

我將如何去實現呢?

+1

能好心編輯您的問題,包括聚合管道,用於測試一些樣本文檔? – chridam

回答

1

您可以展開陣列並在投影后再次將其纏繞。 事情是這樣的:

db.collectionName.aggregate([ 
{$unwind:'$authors'}, 
{$project:{_id:1,count:1,'author.id':'$authors.author.author','author.count':'$authors.count'}}, 
{$group:{_id:{_id:'$_id',count:'$count'},author:{$push:{id:'$author.id',count:'$author.count'}}}}, 
{$project:{_id:0,_id:'$_id._id',count:'$_id.count',author:1}} 
]) 

的輸出將是:

{ 
    "_id" : "581c8c3df1325f68ffd23386", 
    "author" : [ 
     { 
      "id" : "57f246b9e01e6c6f08e1d99a", 
      "count" : 13.0 
     }, 
     { 
      "id" : "5824382511f16d0f3fd5aaf2", 
      "count" : 1.0 
     } 
    ], 
    "count" : 14.0 
}