Mongodb:如何按多个字段分组


在MongoDB中可以使用以下语法对多个字段进行分组并进行聚合:

 db.collection.aggregate([
    { $group : { _id :{field1:" $field1 ", field2:" $field2 "}, count :{ $sum :1}}}
])

以下示例展示了如何在具有以下文档的催收团队中使用此语法:

 db.teams.insertOne({team: " Mavs ", position: " Guard ", points: 31 })
db.teams.insertOne({team: " Mavs ", position: " Guard ", points: 22 })
db.teams.insertOne({team: " Mavs ", position: " Forward ", points: 19 })
db.teams.insertOne({team: " Rockets ", position: " Guard ", points: 26 })
db.teams.insertOne({team: " Rockets ", position: " Forward ", points: 33 })

示例1:按多个字段分组并聚合

我们可以使用下面的代码按“团队”和“位置”进行分组,并统计每个分组的出现次数:

 db.teams.aggregate([
    { $group : { _id : {team: " $team ", position: " $position "}, count :{ $sum :1}}}
])

这将返回以下结果:

 { _id: { team: ' Rockets ', position: ' Forward ' }, count: 1 }
{ _id: { team: ' Mavs ', position: ' Guard ' }, count: 2 }
{ _id: { team: ' Mavs ', position: ' Forward ' }, count: 1 }
{ _id: { team: ' Rockets ', position: ' Guard ' }, count: 1 }

我们还可以进行不同的聚合。例如,我们可以按“团队”和“职位”进行分组,并通过分组求出“分数”的总和:

 db.teams.aggregate([
    { $group : { _id : {team: " $team ", position: " $position "}, sumPoints :{ $sum : " $points "}}}
])

这将返回以下结果:

 { _id: { team: ' Rockets ', position: ' Forward ' }, sumPoints: 33 }
{ _id: { team: ' Mavs ', position: ' Guard ' }, sumPoints: 53 }
{ _id: { team: ' Mavs ', position: ' Forward ' }, sumPoints: 19 }
{ _id: { team: ' Rockets ', position: ' Guard ' }, sumPoints: 26 }

这告诉我们:

  • “火箭队”球员在“前锋”位置上的得分总和为33 分
  • “小牛队”球员在“后卫”位置上的得分总和为53 分

等等。

示例2:按多个字段分组并聚合(然后排序)

我们可以使用下面的代码,按照“队伍”和“位置”进行分组,并通过分组求出“积分”的总和,然后将结果按照“积分”升序排序

 db.teams.aggregate([
    { $group : { _id : {team: " $team ", position: " $position "}, sumPoints :{ $sum : " $points "}}},
    { $sort : { sumPoints :1}}
])

这将返回以下结果:

 { _id: { team: ' Mavs ', position: ' Forward ' }, sumPoints: 19 }
{ _id: { team: ' Rockets ', position: ' Guard ' }, sumPoints: 26 }
{ _id: { team: ' Rockets ', position: ' Forward ' }, sumPoints: 33 }
{ _id: { team: ' Mavs ', position: ' Guard ' }, sumPoints: 53 }

我们可以使用-1按点降序对结果进行排序

 db.teams.aggregate([
    { $group : { _id : {team: " $team ", position: " $position "}, sumPoints :{ $sum : " $points "}}},
    { $sort : { sumPoints :-1}}
])

这将返回以下结果:

 { _id: { team: ' Mavs ', position: ' Guard ' }, sumPoints: 53 }
{ _id: { team: ' Rockets ', position: ' Forward ' }, sumPoints: 33 }
{ _id: { team: ' Rockets ', position: ' Guard ' }, sumPoints: 26 }
{ _id: { team: ' Mavs ', position: ' Forward ' }, sumPoints: 19 }

注意:您可以在此处找到$group的完整文档。

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注