3
我有一組文檔,其中包含不同項目的反饋列表。它看起來是這樣的:MongoDB:計算每個不同值有多少個?
{
{
item: "item_1"
rating: "neutral"
comment: "some comment"
},
{
item: "item_2"
rating: "good"
comment: "some comment"
},
{
item: "item_1"
rating: "good"
comment: "some comment"
},
{
item: "item_1"
rating: "bad"
comment: "some comment"
},
{
item: "item_3"
rating: "good"
comment: "some comment"
},
}
我想一個辦法,找出每個項目多少不同的等級得到。
所以輸出應該是這個樣子:
{
{
item: "item_1"
good: 12
neutral: 10
bad: 67
},
{
item: "item_2"
good: 2
neutral: 45
bad: 8
},
{
item: "item_3"
good: 1
neutral: 31
bad: 10
}
}
這是我做了什麼
db.collection(collectionName).aggregate(
[
{
$group:
{
_id: "$item",
good_count: {$sum: {$eq: ["$rating", "Good"]}},
neutral_count:{$sum: {$eq: ["$rating", "Neutral"]}},
bad_count:{$sum: {$eq: ["$rating", "Bad"]}},
}
}
]
)
輸出的格式看起來正確的,但計數始終爲0 。
我想知道什麼是通過查看相同字段的不同值來總結事情的正確方法?
謝謝!