Mongodb 我们如何使用聚合对不同的匹配案例进行分组?
我有一个用户数据Mongodb 我们如何使用聚合对不同的匹配案例进行分组?,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,我有一个用户数据 users = [{ name : 'z', movie : 'yes', finance : 'no' }, { name : 'zee', movie : 'no', finance : 'yes'}, { name : 'zoo', movie : 'yes' }] 我需要把他们分组 { totalUsers : 3, movieWatch : 2, financeUse
users = [{
name : 'z',
movie : 'yes',
finance : 'no'
},
{
name : 'zee',
movie : 'no',
finance : 'yes'},
{
name : 'zoo',
movie : 'yes'
}]
我需要把他们分组
{
totalUsers : 3,
movieWatch : 2,
financeUsed : 1,
financeNotDone : 1 }
我试着理解聚合,但发现我们可以做一场比赛,或者说我没有正确理解,请帮助我
我不熟悉聚合概念。可以试试
db.getCollection('collectionName').aggregate([
{$group:{
_id: null,
totalUsers: {$sum:1},
movieWatch: {$sum: {$cond: [ { $eq: [ "$movie", 'yes' ] }, 1, 0 ]}},
financeUsed : {$sum: {$cond: [ { $eq: [ "$finance", 'yes' ] }, 1, 0 ]}},
financeNotDone : {$sum: {$cond: [ { $eq: [ "$finance", 'no' ] }, 1, 0 ]}}
}}
]);
我可以试试
db.getCollection('collectionName').aggregate([
{$group:{
_id: null,
totalUsers: {$sum:1},
movieWatch: {$sum: {$cond: [ { $eq: [ "$movie", 'yes' ] }, 1, 0 ]}},
financeUsed : {$sum: {$cond: [ { $eq: [ "$finance", 'yes' ] }, 1, 0 ]}},
financeNotDone : {$sum: {$cond: [ { $eq: [ "$finance", 'no' ] }, 1, 0 ]}}
}}
]);