필터링된 하위 집합
이 페이지의 내용
서론
이 튜토리얼에서는 PyMongo를 사용하여 집계 파이프라인을 구성하고, 컬렉션에서 집계를 수행하고, 샘플 앱을 완료하고 실행하여 결과를 인쇄하는 방법을 배울 수 있습니다. 이 애그리게이션은 다음 작업을 수행합니다.
문서의 하위 집합을 필드 값으로 일치
결과 문서 서식 지정
집계 작업 요약
이 튜토리얼에서는 컬렉션에 있는 문서의 특정 하위 집합을 컬렉션에 쿼리하는 방법을 설명합니다. 결과에는 나이가 가장 어린 엔지니어 세 명을 설명하는 문서가 포함되어 있습니다.
이 예에서는 사람을 설명하는 문서가 포함된 persons
collection 하나를 사용합니다. 각 문서에는 이름, 생년월일, 직업 및 기타 세부 정보가 포함되어 있습니다.
시작하기 전에
이 튜토리얼을 시작하기 전에 애그리게이션 템플릿 앱 지침을 완료하여 작동하는 Python 애플리케이션을 설정하세요.
앱을 설정한 후 애플리케이션에 다음 코드를 추가하여 persons
컬렉션에 액세스합니다.
person_coll = agg_db["persons"]
컬렉션의 기존 데이터를 모두 삭제하고 다음 코드에 표시된 대로 샘플 데이터를 persons
컬렉션에 삽입합니다.
person_coll.delete_many({}) person_data = [ { "person_id": "6392529400", "firstname": "Elise", "lastname": "Smith", "dateofbirth": datetime(1972, 1, 13, 9, 32, 7), "vocation": "ENGINEER", "address": { "number": 5625, "street": "Tipa Circle", "city": "Wojzinmoj", } }, { "person_id": "1723338115", "firstname": "Olive", "lastname": "Ranieri", "dateofbirth": datetime(1985, 5, 12, 23, 14, 30), "gender": "FEMALE", "vocation": "ENGINEER", "address": { "number": 9303, "street": "Mele Circle", "city": "Tobihbo", } }, { "person_id": "8732762874", "firstname": "Toni", "lastname": "Jones", "dateofbirth": datetime(1991, 11, 23, 16, 53, 56), "vocation": "POLITICIAN", "address": { "number": 1, "street": "High Street", "city": "Upper Abbeywoodington", } }, { "person_id": "7363629563", "firstname": "Bert", "lastname": "Gooding", "dateofbirth": datetime(1941, 4, 7, 22, 11, 52), "vocation": "FLORIST", "address": { "number": 13, "street": "Upper Bold Road", "city": "Redringtonville", } }, { "person_id": "1029648329", "firstname": "Sophie", "lastname": "Celements", "dateofbirth": datetime(1959, 7, 6, 17, 35, 45), "vocation": "ENGINEER", "address": { "number": 5, "street": "Innings Close", "city": "Basilbridge", } }, { "person_id": "7363626383", "firstname": "Carl", "lastname": "Simmons", "dateofbirth": datetime(1998, 12, 26, 13, 13, 55), "vocation": "ENGINEER", "address": { "number": 187, "street": "Hillside Road", "city": "Kenningford", } } ] person_coll.insert_many(person_data)
튜토리얼
엔지니어를 위한 매치 단계 추가
먼저 vocation
필드 값이 "ENGINEER"
인 문서를 찾는 $match 단계를 추가합니다.
pipeline.append({ "$match": { "vocation": "ENGINEER" } })
정렬 단계를 추가하여 가장 나이가 어린 사람부터 가장 나이가 많은 사람까지 정렬합니다
다음으로, dateofbirth
필드를 기준으로 문서를 내림차순으로 정렬하여 가장 어린 사람을 먼저 나열하는 $sort 단계를 추가합니다. Python 사전은 요소의 순서를 유지하지 않으므로 SON``or ``OrderedDict
객체를 대신 사용하세요.
pipeline.append({ "$sort": { "dateofbirth": -1 } })
결과를 3개만 표시하도록 제한 단계 추가
그 후 파이프라인에 $limit 단계를 추가하여 결과에서 처음 3개의 문서만 출력합니다.
pipeline.append({ "$limit": 3 })
설정되지 않은 단계를 추가하여 불필요한 필드 제거
마지막으로 $unset 단계를 추가합니다. $unset
단계는 결과 문서에서 불필요한 필드를 제거합니다.
pipeline.append({ "$unset": [ "_id", "address" ] })
팁
다른 필드가 있는 문서가 컬렉션에 추가되는 경우 집계 파이프라인이 수정되지 않도록 하려면 $project
대신 $unset
연산자를 사용합니다.
결과 해석
집계된 결과에는 3개의 문서가 포함되어 있습니다. 문서는 "ENGINEER"
라는 직업을 가진 사람 3명을 가장 나이 어린 사람부터 나이 많은 사람 순으로 표시합니다. 결과에서는 _id
및 address
필드가 생략됩니다.
{ 'person_id': '7363626383', 'firstname': 'Carl', 'lastname': 'Simmons', 'dateofbirth': datetime.datetime(1998, 12, 26, 13, 13, 55), 'vocation': 'ENGINEER' } { 'person_id': '1723338115', 'firstname': 'Olive', 'lastname': 'Ranieri', 'dateofbirth': datetime.datetime(1985, 5, 12, 23, 14, 30), 'gender': 'FEMALE', 'vocation': 'ENGINEER' } { 'person_id': '6392529400', 'firstname': 'Elise', 'lastname': 'Smith', 'dateofbirth': datetime.datetime(1972, 1, 13, 9, 32, 7), 'vocation': 'ENGINEER' }
이 튜토리얼의 전체 코드를 보려면 완료된 필터링된 하위 집합 앱을 GitHub에서 참조하세요.