실제 데이터를 이용한 aggregation 실습 환경 구축

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

2. 실제 데이터를 이용한 aggregation 실습 환경 구축

2.1. 미국 zip code 데이터 collection

  • 다음과 같은 형태의 JSON 데이터로 구성됨
In [ ]:
{
  "_id": "10280",
  "city": "NEW YORK",
  "state": "NY",
  "pop": 5574,
  "loc": [
    -74.016323,
    40.710537
  ]
}
  • The _id field holds the zip code as a string.
  • The city field holds the city name. A city can have more than one zip code associated with it as different sections of the city can each have a different zip code.
  • The state field holds the two letter state abbreviation.
  • The pop field holds the population.
  • The loc field holds the location as a latitude longitude pair.

2.2. 미국 restaurant 데이터 collection

  • 다음과 같은 형태의 JSON 데이터로 구성됨
In [ ]:
{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
체계적으로 전문가 레벨까지 익힐 수 있도록 온라인 강의 로드맵을 제공합니다

2.3. 파일로 mongodb 데이터베이스/컬렉션 만드는 방법

실습
1. 터미널로 접속
2. wget http://media.mongodb.org/zips.json
3. wget https://raw.githubusercontent.com/mongodb/docs-assets/primer-dataset/primer-dataset.json
4. mongoimport -u davelee --db test_db --collection zip --drop --file zips.json --authenticationDatabase admin
5. mongoimport -u davelee --db test_db --collection restaurant --drop --file primer-dataset.json --authenticationDatabase admin

2.4. wget 명령 알아두기

2.5. mongoimport & mongoexport 명령 알아두기

  • mongoimport
    • 파일로부터 db 생성
    • primer-dataset.json 파일을 다운로드 받은 디렉토리에서 실행하거나, primer-dataset.json 파일 경로를 명확히 지정해줄 것
    • mongoimport -u davelee --db test_db --collection zip --drop --file primer-dataset.json --authenticationDatabase admin
      • mongoimport 옵션
        • -u 사용자이름
        • --db 데이터베이스이름
        • --collection 생성할컬렉션이름
        • --drop : 데이터베이스/컬렉션 생성 전에 데이터베이스를 지워라
        • --file 파일명 : 컬렉션 생성할 데이터가 저장된 파일
        • --authenticationDatabase admin : 데이터베이스/컬렉션 생성시 해당 옵션이 없으면 인증 에러가 나는 경우가 있음
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
체계적으로 전문가 레벨까지 익힐 수 있도록 온라인 강의 로드맵을 제공합니다
이해하고 실습하기
* mongoexport
- db의 데이터를 파일에 백업
- mongoexport -u davelee --db test_db --collection zip -o exported-primer-dataset.json --authenticationDatabase admin
In [55]:
import pymongo
In [56]:
username = 'davelee'
password = 'korea123'
In [57]:
connection = pymongo.MongoClient('mongodb://%s:%s@www.funcoding.xyz' % (username, password))
db = connection.test_db
In [58]:
# test_db 에는 어떤 컬렉션이 있을까?
db.collection_names()
Out[58]:
['restaurant', 'test_db', 'zip']
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
체계적으로 전문가 레벨까지 익힐 수 있도록 온라인 강의 로드맵을 제공합니다
In [59]:
# 컬렉션 객체 
db.zip
Out[59]:
Collection(Database(MongoClient(host=['www.funcoding.xyz:27017'], document_class=dict, tz_aware=False, connect=True), 'test_db'), 'zip')
In [5]:
db.restaurant
Out[5]:
Collection(Database(MongoClient(host=['www.funcoding.xyz:27017'], document_class=dict, tz_aware=False, connect=True), 'test_db'), 'restaurant')

2.6. find() 의 limit 옵션 사용해보기, 옵션 사용하지 않으면 데이터가 많아서 노트북이 다운될 수 있음

In [6]:
result = db.zip.find(limit=5)
for record in result:
    print(record)
{'_id': '01001', 'city': 'AGAWAM', 'loc': [-72.622739, 42.070206], 'pop': 15338, 'state': 'MA'}
{'_id': '01002', 'city': 'CUSHMAN', 'loc': [-72.51565, 42.377017], 'pop': 36963, 'state': 'MA'}
{'_id': '01005', 'city': 'BARRE', 'loc': [-72.108354, 42.409698], 'pop': 4546, 'state': 'MA'}
{'_id': '01007', 'city': 'BELCHERTOWN', 'loc': [-72.410953, 42.275103], 'pop': 10579, 'state': 'MA'}
{'_id': '01008', 'city': 'BLANDFORD', 'loc': [-72.936114, 42.182949], 'pop': 1240, 'state': 'MA'}
In [7]:
result = db.restaurant.find(limit=1)
for record in result:
    print(record)
{'_id': ObjectId('5a095da1e8393b01d3208bb4'), 'address': {'building': '1007', 'coord': [-73.856077, 40.848447], 'street': 'Morris Park Ave', 'zipcode': '10462'}, 'borough': 'Bronx', 'cuisine': 'Bakery', 'grades': [{'date': datetime.datetime(2014, 3, 3, 0, 0), 'grade': 'A', 'score': 2}, {'date': datetime.datetime(2013, 9, 11, 0, 0), 'grade': 'A', 'score': 6}, {'date': datetime.datetime(2013, 1, 24, 0, 0), 'grade': 'A', 'score': 10}, {'date': datetime.datetime(2011, 11, 23, 0, 0), 'grade': 'A', 'score': 9}, {'date': datetime.datetime(2011, 3, 10, 0, 0), 'grade': 'B', 'score': 14}], 'name': 'Morris Park Bake Shop', 'restaurant_id': '30075445'}
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
체계적으로 전문가 레벨까지 익힐 수 있도록 온라인 강의 로드맵을 제공합니다

2.7. pprint 라이브러리 활용하기 - 알아보기 쉽게 출력하기

In [8]:
from pprint import pprint

result = db.restaurant.find(limit=3)
for record in result:
    pprint(record)
{'_id': ObjectId('5a095da1e8393b01d3208bb4'),
 'address': {'building': '1007',
             'coord': [-73.856077, 40.848447],
             'street': 'Morris Park Ave',
             'zipcode': '10462'},
 'borough': 'Bronx',
 'cuisine': 'Bakery',
 'grades': [{'date': datetime.datetime(2014, 3, 3, 0, 0),
             'grade': 'A',
             'score': 2},
            {'date': datetime.datetime(2013, 9, 11, 0, 0),
             'grade': 'A',
             'score': 6},
            {'date': datetime.datetime(2013, 1, 24, 0, 0),
             'grade': 'A',
             'score': 10},
            {'date': datetime.datetime(2011, 11, 23, 0, 0),
             'grade': 'A',
             'score': 9},
            {'date': datetime.datetime(2011, 3, 10, 0, 0),
             'grade': 'B',
             'score': 14}],
 'name': 'Morris Park Bake Shop',
 'restaurant_id': '30075445'}
{'_id': ObjectId('5a095da1e8393b01d3208bb5'),
 'address': {'building': '469',
             'coord': [-73.961704, 40.662942],
             'street': 'Flatbush Avenue',
             'zipcode': '11225'},
 'borough': 'Brooklyn',
 'cuisine': 'Hamburgers',
 'grades': [{'date': datetime.datetime(2014, 12, 30, 0, 0),
             'grade': 'A',
             'score': 8},
            {'date': datetime.datetime(2014, 7, 1, 0, 0),
             'grade': 'B',
             'score': 23},
            {'date': datetime.datetime(2013, 4, 30, 0, 0),
             'grade': 'A',
             'score': 12},
            {'date': datetime.datetime(2012, 5, 8, 0, 0),
             'grade': 'A',
             'score': 12}],
 'name': "Wendy'S",
 'restaurant_id': '30112340'}
{'_id': ObjectId('5a095da1e8393b01d3208bb6'),
 'address': {'building': '351',
             'coord': [-73.98513559999999, 40.7676919],
             'street': 'West   57 Street',
             'zipcode': '10019'},
 'borough': 'Manhattan',
 'cuisine': 'Irish',
 'grades': [{'date': datetime.datetime(2014, 9, 6, 0, 0),
             'grade': 'A',
             'score': 2},
            {'date': datetime.datetime(2013, 7, 22, 0, 0),
             'grade': 'A',
             'score': 11},
            {'date': datetime.datetime(2012, 7, 31, 0, 0),
             'grade': 'A',
             'score': 12},
            {'date': datetime.datetime(2011, 12, 29, 0, 0),
             'grade': 'A',
             'score': 12}],
 'name': 'Dj Reynolds Pub And Restaurant',
 'restaurant_id': '30191841'}