按primary和secondary角色字段合并分组,统计各角色用户数量
How to Count User Roles by Primary and Secondary Fields
Alright, let's figure out how to count those user roles properly. You've got a list of users with primary and optional secondary roles, and you want to tally up how many times each role appears across both fields—here's how to do it in a couple of common scenarios:
1. Using Plain JavaScript
If you're working with the user data as a local array in JS, you can use flatMap to collect all valid roles, then reduce to count occurrences:
const users = [ { _id: 1, roles: { primary: 'Cook', secondary: null } }, { _id: 2, roles: { primary: 'Waiter', secondary: 'Cashier' } }, { _id: 3, roles: { primary: 'Cashier', secondary: 'Bar Tender' } } ]; // Step 1: Collect all non-null roles from primary and secondary fields const allRoles = users.flatMap(user => { const rolesList = [user.roles.primary]; // Only add secondary role if it's not null if (user.roles.secondary !== null) { rolesList.push(user.roles.secondary); } return rolesList; }); // Step 2: Count occurrences of each role const roleCounts = Object.entries( allRoles.reduce((counts, role) => { counts[role] = (counts[role] || 0) + 1; return counts; }, {}) ).map(([role, count]) => ({ role, count })); console.log(roleCounts); // Output: [ // { role: 'Cook', count: 1 }, // { role: 'Waiter', count: 1 }, // { role: 'Cashier', count: 2 }, // { role: 'Bar Tender', count: 1 } // ]
Breakdown:
flatMapconverts each user into an array of their valid roles (skippingnullsecondary roles) and flattens the result into a single list of roles.reduceiterates over the role list to build an object where keys are roles and values are their counts.- Finally, we convert that object into your desired array format using
Object.entries()andmap().
2. Using MongoDB Aggregation
If your user data is stored in MongoDB, you can use an aggregation pipeline to compute the counts directly in the database:
db.users.aggregate([ // Create an array of non-null roles for each user { $project: { roles: { $filter: { input: ['$roles.primary', '$roles.secondary'], cond: { $ne: ['$$this', null] } } } } }, // Split each role in the array into its own document { $unwind: '$roles' }, // Group by role and count occurrences { $group: { _id: '$roles', count: { $sum: 1 } } }, // Rename fields to match your desired output format { $project: { _id: 0, role: '$_id', count: 1 } } ])
Breakdown:
$project+$filtercreates an array containing only non-null roles for each user.$unwindconverts each role in the array into a separate document, making it easy to group.$grouptallies up the number of times each role appears.- The final
$projectrenames_idtoroleand removes the original_idfield to match your requested output structure.
内容的提问来源于stack exchange,提问作者Combustible Pizza
相关产品推荐
相关产品推荐

