2014-09-05 253 views
1

我正在學習MongoDB中的聚合。我正在與集合:Mongodb聚合集合

    { 
          "body" : "" 
    , 
        "email" : "[email protected]", 
        "author" : "Linnie Weigel" 
      }, 
      { 
        "body" : "" 
    , 
        "email" : "[email protected]", 
        "author" : "Dinah Sauve" 
      }, 
      { 
        "body" : "" 
    , 
        "email" : "[email protected]", 
        "author" : "Zachary Langlais" 
      } 
      { 
        "body" : "" 
    , 
        "email" : "[email protected]", 
        "author" : "Jesusa Rickenbacker" 
      } 
    ] 

我試圖獲得每個作者的身體數量。但是當我執行聚合MongoDB的命令總和時,結果是1(因爲結構只有一個元素)。我該如何做這個操作?我試着用$ addToSet。但我不知道如何獲得收集的每個元素並進行操作。

+0

能否請您包括您使用的代碼?你的mongodb大學作業也是這樣嗎? – 2014-09-06 00:10:31

+0

你說「執行命令總和」 - 沒有這樣的命令。您是否在討論$ group階段,您可以使用$ sum運算符來獲得您的答案(只要您在正確的字段上進行分組)。 – 2014-09-06 01:11:42

+0

我的代碼是var group = {$ group:{_ id:「$ author」,total:{$ addToSet:「$ comments.author」}}}: – 2014-09-06 04:35:38

回答

2

爲了統計每個作者的評論,你想要該作者的$group$sum的發生次數。基本上只是一個「$總和:1」操作。但是,根據您自己的評論以及您的部分數據清單中的結尾括號,您似乎有「評論」這樣的數組。對於您需要$unwind首先處理:

db.collection.aggregate([ 
    { "$unwind": "$comments" }, 
    { "$group": { 
     "_id": "$comments.author", 
     "count": { "$sum": 1 } 
    }} 
]) 

將由筆者得到總的所有作者的評論對整個集合。如果你只是作者獲得總評價每個文檔(或看起來像一個博客帖子模型)使用文檔_id作爲組聲明的一部分,那麼後:

db.collection.aggregate([ 
    { "$unwind": "$comments" }, 
    { "$group": { 
     "_id": { 
      "_id": "$_id" 
      "author": "$comments.author" 
     }, 
     "count": { "$sum": 1 } 
    }} 
]) 

如果你再想摘要每個文檔的作者計算只有在陣列中的所有作者返回一個單一的文件,然後使用$addToSet從這裏,與其他$group流水線階段:

db.collection.aggregate([ 
    { "$unwind": "$comments" }, 
    { "$group": { 
     "_id": { 
      "_id": "$_id" 
      "author": "$comments.author" 
     }, 
     "count": { "$sum": 1 } 
    }}, 
    { "$group": { 
     "_id": "$_id._id", 
     "comments": { 
      "$addToSet": { 
       "author": "$_id.author", 
       "count": "$count" 
      } 
     } 
    }} 
]) 

不過說真的,筆者值已經獨一無二的「套「並沒有以任何方式排列,所以你可以用來改變它後首次引入$sort有被評論數排序列表發:

db.collection.aggregate([ 
    { "$unwind": "$comments" }, 
    { "$group": { 
     "_id": { 
      "_id": "$_id" 
      "author": "$comments.author" 
     }, 
     "count": { "$sum": 1 } 
    }}, 
    { "$sort": { "_id._id": 1, "count": -1 } }, 
    { "$group": { 
     "_id": "$_id._id", 
     "comments": { 
      "$push": { 
       "author": "$_id.author", 
       "count": "$count" 
      } 
     } 
    }} 
])