2017-08-14 76 views
0

中編寫條件語句我很新的蒙戈,並有關於集合查詢有條件計算一個問題:MongoDB的 - 如何彙總查詢

我有一個評論集合,每個文檔包含景氣指數。我想:

1)項

2)組評審獲取平均景氣指數爲跨該商品的所有評論每個項目和排序的評語此

3)獲得總#爲每個項目組

4)獲取的陽性情緒的評價總#每個項目(例如,與情緒分數#評論> 75)

5)獲取的負面情緒的評價總#每個項目(例如,#情緒分數爲的評論75)

到目前爲止,我有以下查詢覆蓋1-3,但不知道如何在這裏得到4/5,以及:

db.reviews.aggregate( 
    {"$group" : 
     {_id: "$item", 
     sentiment: {$avg : "$sentimentScore"}, 
     count: {$sum: 1 } 
     } 
    }, 
    {"$sort": { sentiment: -1 } } 
) 
+0

您需要提供樣本文件 –

+0

Januka嗨,文件的唯一重要字段中所示的那些代碼 - 「sentimentScore」是0到100之間的一個#,以及是項目名稱的「item」。我想要做的就是添加代碼我有這樣的我有2個新字段返回給我的每個組項目,其中一個是該組中的項目#情緒分數<75和一個爲> 75 – jbug123

回答

0

我假設你想sentiment分別有count字段與負值和正值與給定的門檻,即positive - >75negative - <75,即積極情緒總數和消極情緒總數以及總情緒。

db.sentiments.aggregate([ 
    {"$group" : 
     {_id: "$item", 
     sentiment: {$avg : "$sentiment_score"}, 
     postiive_sentiments: {$sum: { $cond: { if: { $gt: [ "$sentiment_score", 75 ] }, then: 1, else: 0 } }}, 
     negative_sentiments: {$sum: { $cond: { if: { $lt: [ "$sentiment_score", 75 ] }, then: 1, else: 0 } }}, 
     count: {$sum: 1 } 
     } 
    }, 
    {"$sort": { sentiment: -1 } } 
]) 

的樣本數據:

{ "_id" : ObjectId("5991329ea37dbc24842a68be"), "item" : "test1", "sentiment_score" : 50 } 
{ "_id" : ObjectId("599132a2a37dbc24842a68bf"), "item" : "test1", "sentiment_score" : 40 } 
{ "_id" : ObjectId("599132a4a37dbc24842a68c0"), "item" : "test1", "sentiment_score" : 80 } 
{ "_id" : ObjectId("599132aba37dbc24842a68c1"), "item" : "test2", "sentiment_score" : 80 } 
{ "_id" : ObjectId("599132ada37dbc24842a68c2"), "item" : "test2", "sentiment_score" : 30 } 
{ "_id" : ObjectId("599132b0a37dbc24842a68c3"), "item" : "test2", "sentiment_score" : 38 } 
{ "_id" : ObjectId("599132b6a37dbc24842a68c4"), "item" : "test3", "sentiment_score" : 78 } 
{ "_id" : ObjectId("599132b9a37dbc24842a68c5"), "item" : "test3", "sentiment_score" : 88 } 
{ "_id" : ObjectId("599132bba37dbc24842a68c6"), "item" : "test3", "sentiment_score" : 58 } 
{ "_id" : ObjectId("599132c4a37dbc24842a68c7"), "item" : "test3", "sentiment_score" : 98 } 
{ "_id" : ObjectId("599132cba37dbc24842a68c8"), "item" : "test4", "sentiment_score" : 65 } 
{ "_id" : ObjectId("599132d2a37dbc24842a68c9"), "item" : "test4", "sentiment_score" : 30 } 
{ "_id" : ObjectId("599132d6a37dbc24842a68ca"), "item" : "test4", "sentiment_score" : 10 } 

//結果:

{ "_id" : "test3", "sentiment" : 80.5, "negative_sentiments" : 3, "positive_sentiments" : 1, "count" : 4 } 
{ "_id" : "test1", "sentiment" : 56.666666666666664, "negative_sentiments" : 1, "positive_sentiments" : 2, "count" : 3 } 
{ "_id" : "test2", "sentiment" : 49.333333333333336, "negative_sentiments" : 1, "positive_sentiments" : 2, "count" : 3 } 
{ "_id" : "test4", "sentiment" : 35, "negative_sentiments" : 0, "positive_sentiments" : 3, "count" : 3 } 
+0

謝謝!工作很好。 – jbug123