因此,我有一个集合,用于存储与用户相关的文档,其结构如下:
{_id: "hofjew233332j4", userId: "fhewojfw34324", achievementUnlocked: true };
我想要做的是使用聚合和下划线能够按用户 ID 对文档进行分组,然后计算其记录的解锁百分比设置为 true,这样生成的文档将如下所示:
{_id: "fhewojfw34324(userId)", unlockPercentage: 40 (achievementUnlocked: true / all docs) }
我可以在只检索一次文档的情况下完成此操作吗?
最佳答案
首先按计数 achievementUnlocked
true
计数进行分组,然后在项目中使用以下聚合来计算百分比
:
db.collectionName.aggregate([{
"$group": {
"_id": "$userId",
"achievementUnlockedTrueCount": {
"$sum": {
"$cond": {
"if": {
"$eq": ["$achievementUnlocked", true] //count achievementUnlocked = true count
},
"then": 1,
"else": 0
}
}
},
"totalCount": {
"$sum": 1 // get total count of grouped documents
}
}
}, {
"$project": {
"unlockPercentage": {
"$multiply": [{
"$divide": ["$achievementUnlockedTrueCount", "$totalCount"] //used this in project to caculate %
}, 100]
}
}
}]).pretty()
关于javascript - 在 meteor 中使用mongo聚合来总计解锁/锁定集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31931999/