실제 데이터를 이용한 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
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 : 데이터베이스/컬렉션 생성시 해당 옵션이 없으면 인증 에러가 나는 경우가 있음
 
 
- mongoimport 옵션
 
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
                                                가장 빠르게 풀스택 개발자가 될 수 있도록, 최적화된 로드맵을 제공합니다
                                            
이해하고 실습하기
* mongoexport
- db의 데이터를 파일에 백업
- mongoexport -u davelee --db test_db --collection zip -o exported-primer-dataset.json --authenticationDatabase admin
* 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]:
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
                                                체계적으로 전문가 레벨까지 익힐 수 있도록 온라인 강의 로드맵을 제공합니다
                                            In [59]:
# 컬렉션 객체 
db.zip
Out[59]:
In [5]:
db.restaurant
Out[5]:
2.6. find() 의 limit 옵션 사용해보기, 옵션 사용하지 않으면 데이터가 많아서 노트북이 다운될 수 있음¶
In [6]:
result = db.zip.find(limit=5)
for record in result:
    print(record)
In [7]:
result = db.restaurant.find(limit=1)
for record in result:
    print(record)
본 자료와 같이 IT 기술을 잘 정리하여, 온라인 강의로 제공하고 있습니다
                                                가장 빠르게 풀스택 개발자가 될 수 있도록, 최적화된 로드맵을 제공합니다
                                            2.7. pprint 라이브러리 활용하기 - 알아보기 쉽게 출력하기¶
In [8]:
from pprint import pprint
result = db.restaurant.find(limit=3)
for record in result:
    pprint(record)
 
                                                    