온라인 강의 자료모음 기업교육

pymongo aggregation 작성 스타일과 참고사항

이해하기 쉽고, 장황하지 않은 자료를 기반으로 강의를 진행합니다.
AI · 풀스택 · 데이터 로드맵 Dave Lee 한 강사가 설계부터 강의까지 모두
사이트 바로가기

8. pymongo aggregation 작성 스타일과 참고사항

  • 코드 작성 스타일 예제
In [53]:
username = 'davelee'
password = 'korea123'
connection = pymongo.MongoClient('mongodb://%s:%s@www.funcoding.xyz' % (username, password))
db = connection.test_db

# pipeline 을 리스트로 만들고, dictionary 타입으로 append 해서 파이프라인의 가독성을 높임
pipelines = list()  
pipelines.append({'$group' : {'_id' : '$state', 'total_pop' : {'$sum' : '$pop'}}})
pipelines.append({'$match' : {'total_pop' : {'$gte' : 10 * 1000 * 1000}}})

results = db.zip.aggregate(pipelines)

for doc in results:
    # 필요한 데이터만 추출 가능
    print(doc['_id'], doc['total_pop'])
CA 29754890
FL 12686644
PA 11881643
NY 17990402
OH 10846517
IL 11427576
TX 16984601
In [ ]:
username = ''
password = ''
connection = pymongo.MongoClient('mongodb://%s:%s@www.funcoding.xyz' % (username, password))
db = connection.test_db

pipelines = list()
pipelines.append({ '$group': { '_id': { 'state': "$state", 'city': "$city" }, 'pop': { '$sum': "$pop" }}})
pipelines.append({ '$group': { '_id': "$_id.state", 'avg_city_pop': { '$avg': "$pop" }}})

results = db.zip.aggregate(pipelines)

for doc in results:
    print(doc)

참고1: Ubuntu 22.04/24.04에서 MongoDB 설치 (Community Edition)

  • 공식 문서: https://www.mongodb.com/docs/manual/installation/
  • apt-key 는 폐기되었으므로 GPG 키를 /usr/share/keyrings 에 저장한 뒤 repo 리스트를 추가합니다.
  • 예시(서버 7.0):
    • curl -fsSL https://pgp.mongodb.com/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
    • echo "deb [ arch=amd64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -sc)/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
    • sudo apt-get update && sudo apt-get install -y mongodb-org
    • sudo systemctl enable --now mongod

참고5: 기존 mongodb CRUD (deprecated 라는 용어를 알아두세요 - 예전에 있었지만, 이제 안쓸 예정이다. 호환성을 위해서만 남겨둔다.)

  • Mongodb CRUD (deprecated)
    • insert

      • db.person.insert({ "name" : "aaron", "age" : 31, "regdate" : new Date() })
    • update

      • db.person.update({ name : "aaron" }, { $set : { gender : "M" }})
    • find / findOne

      • db.person.find()
      • db.person.findOne()
      • db.person.find({ name : "aaron" })
      • db.person.find({ name : "aaron", or : [{ age : 30 }, { age : 21 }] })
      • db.person.find({ name : "aaron", nor : [{ age : 20 }, { age : 21 }] })
      • db.person.find({ age : { in : [20, 21] }})
      • db.person.find({ age : { nin : [20, 21] }})
      • db.person.findOne({name : 'Aaron'}, {name : 1, regdate : 1})
      • db.person.find({ name : null })
      • db.person.find().sort({ name : 1 }) # DESC
      • db.person.find().sort({ name : -1 }) # ASC
      • db.person.find().limit(2)
      • db.person.find().limit(2).skip(2) # 2건너 뛰고 2개 가져옴
      • db.person.find({ name : { $exists : false } }) # 특정 필드가 없는 문제 가져옴
    • count

      • db.person.count()
      • db.person.find({ name : "aaron" }).count()
    • remove

      • db.person.remove({ name : "aaron" })
    • drop - collection 삭제

      • db.person.drop()