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점 입니다.
- ‘가드’ 포지션의 ‘Mavs’ 선수들이 득점한 점수의 합은 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 에 대한 전체 문서는 여기에서 찾을 수 있습니다.