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

이해하기 쉽고, 장황하지 않은 자료를 기반으로 강의를 진행합니다.
잔재미코딩 소식 공유
좀더 제약없이, IT 컨텐츠를 공유하고자, 자체 온라인 사이트와, 다음 두 채널도 오픈하였습니다
응원해주시면, 곧 좋은 컨텐츠를 만들어서 공유하겠습니다
●  잔재미코딩 뉴스레터 오픈 [구독해보기]
●  잔재미코딩 유투브 오픈 [구독해보기]

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 버전별 mongodb 설치

  • https://docs.mongodb.com/manual/installation/
  • community edition 설치

  • terminal에서 아래의 명령어 차례대로 수행

    • sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
    • lsb_release -a (ubuntu 버젼 확인)
    • ubuntu 12.04의 경우
    • ubuntu 14.04의 경우
    • ubuntu 16.04의 경우
    • sudo apt-get update
    • sudo apt-get install -y mongodb-org

    • sudo vi /etc/mongod.conf

      • bindIp: 127.0.0.1 -> 0.0.0.0으로 변경
    • sudo service mongod start or restart

    • sudo service mongod status

참고2: mongodb 삭제

  • sudo apt-get purge mongodb-org*

참고4: local machine에서 접속 확인

참고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()