You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按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:

  • flatMap converts each user into an array of their valid roles (skipping null secondary roles) and flattens the result into a single list of roles.
  • reduce iterates 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() and map().

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 + $filter creates an array containing only non-null roles for each user.
  • $unwind converts each role in the array into a separate document, making it easy to group.
  • $group tallies up the number of times each role appears.
  • The final $project renames _id to role and removes the original _id field to match your requested output structure.

内容的提问来源于stack exchange,提问作者Combustible Pizza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:37:27