2015-10-09 16 views
1

我有一個進料收集與樣數據的總和:在春天的MongoDB組一列,並得到另外兩個領域

{ 
"_id" : ObjectId("55deb33dcb9be727e8356289"), 
"userName" : "John", 
"likeCount" : 2, 
"commentCount" : 10, 
} 
, 
{ 
"_id" : ObjectId("55deb33dcb3456e33434d456"), 
"channelName" : "Mark", 
"likeCount" : 5, 
"commentCount" : 10, 
}, 
{ 
"_id" : ObjectId("55acd3434324acd3e4567567"), 
"userName" : "John", 
"likeCount" : 12, 
"commentCount" : 15, 
} 

我想通過「username」的獲得所有組的記錄和總和「likeCount」+「commentCout」。 在MySQL中,我們使用:

select userName,sum(likeCount)+sum(commentCount) as "totalCount" from feed group by userName 

我怎麼能寫上面的查詢聚集?

回答

1

我相信這可以通過添加一個額外的字段,增加了在$project階段likeCountcommentCount領域,然後執行和操作上的那場由userName鍵進行了分組的文件來實現。像這樣的事情在蒙戈查詢:

db.feed.aggregate([ 
    { 
     "$project": { 
      "userName": 1, 
      "sumLikeAndCommentCounts": { 
       "$add": [ "$likeCount", "$commentCount" ] 
      } 
     } 
    }, 
    { 
     "$group": { 
      "_id": "$userName", 
      "totalCount": { 
       "$sum": "$sumLikeAndCommentCounts" 
      } 
     } 
    } 
]) 

OR

你只需要一個管道一步$group在那裏你可以在加法運算插頭作爲一個表達式爲$sum

db.feed.aggregate([  
    { 
     "$group": { 
      "_id": "$userName", 
      "totalCount": { 
       "$sum": { 
        "$add": [ "$likeCount", "$commentCount" ] 
       } 
      } 
     } 
    } 
]) 

上述兩種操作流水線都會產生結果(對於giv EN樣本數據):

{ "_id" : null, "totalCount" : 15 } 
{ "_id" : "John", "totalCount" : 39 } 

春季數據MongoDB的聚集相當於是基於第一個例子,在投影操作使用SpEL andExpression的一個選項:

Aggregation agg = Aggregation.newAggregation( 
    project("id", "userName") 
     .and("likeCount").plus("commentCount").as("sumLikeAndCommentCounts"), 
     //.andExpression("likeCount + commentCount").as("sumLikeAndCommentCounts"), <-- or use expressions 
    group("userName").sum("sumLikeAndCommentCounts").as("totalCount") 
); 
AggregationResults<FeedsTotal> result = 
mongos.aggregate(agg, this.getCollectionName(), FeedsTotal.class); 
+1

感謝chridam ...您幫忙 – Pankaj

+0

不用擔心@Pankaj :-) – chridam

相關問題