First, $group to group
1. Number of employees in each position:
Db.getcollection (' emp '). Aggregate (
[
{' $group ': {
' _id ': ' $job ',
job_count:{' $sum ': 1}
}
}
]
)
2. Total salary for each position
Db.getcollection (' emp '). Aggregate (
[
{' $group ': {
' _id ': ' $job ',
job_salaryt:{' $sum ': ' $salary '}
}
}
]
)
3. Average salary for each position
Db.getcollection (' emp '). Aggregate (
[
{' $group ': {
' _id ': ' $job ',
job_salaryt:{' $sum ': ' $salary '},
job_salary_avg:{' $avg ': ' $salary '}
}
}
]
)
4. Maximum and minimum wage for each position
Db.getcollection (' emp '). Aggregate (
[
{' $group ': {
' _id ': ' $job ',
max_salaryt:{' $max ': ' $salary '},
min_salary:{' $min ': ' $salary '}
}
}
]
)
5. Salary for each position
Db.getcollection (' emp '). Aggregate (
[
{
' $group ': {
' _id ': ' $job ',
' Salary_data ': {' $push ': ' $salary '}
}
}
]
)
6. Personnel of each position
Db.getcollection (' emp '). Aggregate (
[
{
' $group ': {
' _id ': ' $job ',
' Position_name ': {' $addToSet ': ' $name '}//addtoset, if there are duplicate names, keep a
}
}
]
)
Second, the $project the rules of data display
1. Aliases
Db.getcollection (' emp '). Aggregate (
[
{' $project ': {
' _id ': 0
' Position ': ' $job ',
' Name ': 1
}
}
]
)
2. Annual Salary
Db.getcollection (' emp '). Aggregate (
[
{
' $project ': {
' Name ': 1,
' Salary ': {' yearly salary ': {' $multiply ': [' $salary ', 12]}}
}
}
]
)
MongoDB for grouping operations