我有如下收藏。
{
"userId" : "1",
"feedbackGiven" : true
}
{
"userId" : "1",
"feedbackGiven" : false
}
{
"userId" : "1",
"feedbackGiven" : true
}
{
"userId" : "2",
"feedbackGiven" : false
}
{
"userId" : "2",
"feedbackGiven" : true
}
我需要在 userId 上对其进行分组,并获得两个值,分别是totalGivenFeedback计数和错误反馈Given计数。
我在下面的查询中尝试过
db.collection.aggregate([
{
$group: { _id: "$userId", feedbackGiven: { $push : "$feedbackGiven"} }
}
])
这给出如下结果。
{
"_id" : "1",
"feedbackGiven" : [
true,
false,
true
]
}
{
"_id" : "2",
"feedbackGiven" : [
false,
true
]
}
使用我的JavaScript代码中的上述结果,我可以获得总的反馈数量和错误反馈数量。
但是我的问题是,有没有办法使用MongoDB查询来获取它。
我期望得到如下结果。
{
"_id" : "1",
"totalFeedbackGive" : 3,
"falseFeedbackCount" : 1
}
{
"_id" : "2",
"totalFeedbackGive" : 1,
"falseFeedbackCount" : 1
}
谁能给我解决方案?
答案 0 :(得分:1)
您可以在aggregation
下使用
db.collection.aggregate([
{ "$group": {
"_id": "$userId",
"totalFeedbackGive": { "$sum": 1 },
"falseFeedbackCount": {
"$sum": {
"$cond": [
{ "$eq": ["$feedbackGiven", false] },
1,
0
]
}
}
}}
])