INTRO
전체적인 흐름
클라이언트 | 인터넷 망 | 서버 |
브라우저 브라우저에서 동작되는 3가지 코드 html, css, js |
웹 어플리케이션 서버(WAS): Flask 활 | |
gitbash: 커멘드 라인 인터페이스 서버에 접속하기 위해 사용 서버 클라이언트 bash command vi editor ssh: 서버 접속 scp: 파일 전송 ip 주소 user pw 필요 |
-> ip 주소 사용 -> | 서버 시스템 ip 주소를 통해 서버에 도착 서버 -> 22번 포트 -> 서버시스템 |
Studio 3T | mongo DB에 접속하기 위해 사용된것 ip, id(user), pw |
mongoDB ip 주소를 통해 서버에 도착 서버 -> 27017번 포트 -> 서버시스템 |
* nginx, flask, pymongo
데이터 베이스 공부법: CRUD : create read update delete
database, collection(table), document(row)
RDBMS: 고객(아이디, 패스워드, 이름, 주소) : 구매정보(아이디, 상품명, 가격)
NoSQL: 고객(아이디, 패스워드, 이름, 주소) : 구매정보(아이디, 상품명, 가격, 이름, 주소)
->테이블간 관계가 없기 때문에 저장하는 정보의 양이 많아진다.
MongoDB
Studio 3T 설치하기
https://studio3t.com/download-studio3t-free/
Download Studio 3T for MongoDB | Windows, macOS & Linux
Get more done in MongoDB with the right tool. Try Studio 3T for free and enjoy easy import/export, build queries fast, generate code & more.
studio3t.com
Connection
Connect -> New Connection -> 접속 URL 입력 후 Next
기본 구문
https://docs.mongodb.com/v3.6/reference/
Reference — MongoDB Manual
Navigation This version of the documentation is archived and no longer supported.
www.mongodb.com
Create Database
# mongo 라는 이름의 데이터 베이스 생성
use mongo
already on db mongo
# 현재 사용중인 데이터 베이스 확인
db
mongo
# database list 확인
show dbs
*show dbs 실행 시 mongo가 보이지 않는이유
- 데이터 베이스를 생성후에 최소 1개이상의 document를 추가해야 생성된 데이터 베이스가 보입니다.
# document 생성
use mongo
db.user.insert({"name":"andy", "age":29, "email":"andy@gmail.com"})
*show dbs - mongo가 추가된것을 볼 수 있다.
Collection list
구조: server > database > collections > documents
show collections;
Delete Database
# 현재 사용중인 데이터 베이스 삭제
db.dropDatabase()
Create Collection
reference - https://docs.mongodb.com/v3.6/reference/method/db.createCollection/\
db.createCollection() — MongoDB Manual
Navigation This version of the documentation is archived and no longer supported. db.createCollection() Definition db.createCollection(name, options) Changed in version 3.4: Added support for: Creates a new collection or view. Because MongoDB creates a col
www.mongodb.com
option
capped | True로 설정하면 collection의 최대 용량을 설정 (최대 용량의 크기는 size 옵션으로 설정), 설정된 최대용량 이상으로 데이터가 입력되면 오래된 데이터 부터 자동으로 삭제됩니다. |
autoIndex | true로 설정하면 _id 필드에 index가 자동으로 생성됩니다. |
size | 숫자 데이터를 사용하며 collection의 최대 사이즈를 byte 단위로 지정 (최소 4096byte) |
max | 숫자 데이터를 사용하며 최대 document 갯수를 설정 |
# name : collection 이름
db.createCollection(name, [option])
# user 컬렉션을 생성
db.createCollection("test")
# capped와 size, max 옵션을 설정하여 info 컬렉션을 생성
db.createCollection("info1", { capped: true, capped: true, size: 500, max:5 })
# createCollection을 사용하지 않고 article 컬렉션을 생성
db.articles.insert( {"title":"data science", "contents":"mongodb" } )
# 컬렉션 리스트 확인
show collections
Delete Collection
# articles 컬렉션 삭제
db.articles.drop()
Make Document
db.<collection_name>.insert(<document>)
# info 컬렉션에 document 추가
db.info1.insert({ "subject":"python", "level":3 })
db.info1.insert({ "subject":"web", "level":1 })
db.info1.insert({ "subject":"sql", "level":2 })
# 한번에 여러개의 document 추가
# max:5 옵션 제한에 걸려 5개의 데이터가 info1에 들어간다.
db.info1.insert( [
{ "subject":"python", "level":1 },
{ "subject":"css", "level":2 },
{ "subject":"js", "level":3 },
{ "subject":"scss", "level":4 },
{ "subject":"web", "level":5 },
{ "subject":"flask", "level":6 },
{ "subject":"nginx", "level":7 },
])
과거 데이터를 삭제하여 최신 데이터 상태를 유지한다.
ex) 로그 기록
Delete Document: remove()
# level2인 데이터 삭제 : capped 제약조건이 걸려있는 컬렉션의 도큐먼트는 삭제가 안됩니다.
db.info.remove( {level:2} )
Read Document: find({})
reference: https://docs.mongodb.com/manual/reference/method/db.collection.find/index.html
db.collection.find() — MongoDB Manual
Docs Home → MongoDB Manual db.collection.find(query, projection, options)mongosh MethodThis page documents a mongosh method. This is not the documentation for database commands or language-specific drivers, such as Node.js.For the database command, see t
www.mongodb.com
db.collection.find(query, projection)
query : document 조회 조건을 설정. 모든 document를 조회 할때는 ({})를 사용
projection : document를 조회할때 보여지는 필드(컬럼)를 정의
비교연산자 논리연산자 사용해서 find
db.info1.find({level: {$gte: 4}});
db.info1.find({subject: {$in: ['flask', 'nginx']}});
projection
READ : documents : projection: select columns
document를 조회할때 보여지는 필드(컬럼)를 정의합니다.
# subject와 comments만 출력되도록 find
# 설정을 true 값을 설정하던가 false 값을 설정합니다. ( _id는 따로 설정을 안하면 true )
## name, age 컬럼 출력
db.user.find({},{name:ture, age:true})
## age 컬럼 제외하고 출력
db.user.find({},{age:false})
## id 제외하고 출력
db.user.find({},{_id:flase, name: true, age: true})
{}: 전체출력
_id 제외한 컬럼에 true, false를 섞어서 샤용불가능하다.
졍렬: sort
document를 정렬시켜 줍니다.
'sort({key: value})' 와 같은 포멧으로 사용을 하며 key는 정렬할 필드명을 작성하고, value는
오름차순은 1, 내림차순을 -1을 넣어주면 됩니다.
# info 컬렉션의 document를 level 오름차순으로 정렬
db.info.find().sort({"level":1})
# info 컬렉션의 document를 level 내림차순으로 정렬
db.info.find().sort({"level":-1})
# level을 기준으로 내림차순으로 정렬한 후 subject를 기준으로 오름차순으로 정렬
db.info.find().sort({"level":-1, "subject":1})
출력 데이터 갯수 제한: limit
limit을 사용하면 document출력 결과의 수룰 제한할수 있습니다.
# document의 결과를 3개 까지만 출력
db.info.find().limit(3)
# document의 결과를 level로 내림차순으로 정렬하고 3개까지만 출력
db.info.find().sort({"level":-1}).limit(3)
데이터를 스킵해서 출력: skip
skip을 검색한 document의 결과의 시작부분을 설정할때 사용합니다.
# document를 3번째 부터 출력
db.info.find().skip(2)
* limit, skip을 함께 사용해서 mysql의 limit과 같이 사용할수 있습니다.
수정: UPDATE documents: update()
reference- https://docs.mongodb.com/manual/reference/command/update/index.html
db.collection.update( query, update, { upsert: <bool>, multi: <bool> })
upsert : insert와 update의 합성어 (데이터가 있으면 update, 없으면 insert 한다는 의미)
multi : true로 설정되면 여려개의 document를 수정합니다. 기본값은 false
UPDATE: $set, $unset
$set을 사용하면 특정 document의 필드를 수정할수 있습니다.
$unset를 사용하면 특정 document의 필드 제거할수 있습니다.
# python의 level을 3으로 수정 (한개의 데이터만 수정)
db.info.update( { subject: "java" }, { $set: { level: 4 } } )
# level 2를 level 1로 수정 (여러개의 데이터 수정)
db.info.update(
{ level: 2 },
{ $set: { level: 1 } },
{ multi: true }
)
# subject가 sass인 document의 level필드 삭제
db.info.update(
{ subject: "sass" },
{ $unset: {level: 1} }
)
* level: 1의 1은 true를 의미합니다.
# level이 2이하인 데이터를 1로 수정하기
db.info.update(
{ level: {$lte: 2} },
{ $set: {level: 1} },
{ multi: 1 }
)
# level이 없는 데이터 level 추가하기
db.info.update(
{ level: {$exists: false} },
{ $set: {level: 2} },
{ multi: 1 }
)
Function: pagenation function
자바스크립트 문법으로 함수 작성이 가능합니다.
# skip 함수
var showSkip = function(start){
return db.info.find().skip(start)
}
showSkip(3)
# pagenation
var pagenation = function(page, pageblock){
return db.info.find().skip((page-1)*pageblock).limit(pageblock)
}
pagenation(2, 3)
정리
create | insert(): [{data1}, {data2}] |
read | find(): (query, projection) : 연산자($gt, $and, $in) |
update | update(): (query, update data, option) : $set |
delete | drop(): (query) |
Pymongo
MongoDB를 Python에서 사용할수있도록 도와주는 ORM
import requests, pymongo
import pandas as pd
Connect Server
# client 연결
client = pymongo.MongoClient('mongodb://test:testpw@43.201.104.0:27017')
client
Create or Connect Database
# 데이터 베이스 목록 출력
list(client.list_databases())
# 데이터 베이스에 접속 및 생성
db = client.mongo
db
CRUD
Create
Read
Update
Delete
Collection
READ Collection
# 데이터 베이스의 컬렉션 리스트 확인
db.list_collection_names()
CREATE Collection
# 컬렉션 선택 생성
collection = db.info
collection
UPDATE Collection
db.user.rename('users')
DELETE Collection
# 컬렉션 선택 및 삭제
collection = db.info1
collection.drop()
# 데이터 베이스의 컬렉션 리스트 확인
# db.list_collection_names()
Document
READ Document
# 한개의 도큐먼트 가져오기
document = collection.find_one({"subject":"python"})
document
# 모든 도큐먼트 가져오기
documents = collection.find()
documents
# 도큐먼트 리스트로 형변환해서 data 변수에 저장
data = list(documents)
print(len(data), data)
# pandas DataFrame 으로 변환
df = pd.DataFrame(data)
df.tail()
# 데이터를 한번 읽으면 데이터가 사라짐
list(documents)
# 도큐먼트의 갯수를 가져옴
count = collection.count_documents({})
count
# 레벨이 2이상인 도큐먼트를 subject 내림차순으로 정렬
documents = collection.find({"level": {"$gte": 2}}).sort("subject", pymongo.DESCENDING)
data = pd.DataFrame(list(documents))
data
CREATE Documnet
# 한개의 대이터 저장 - insert_one
data = {"subject":"css", "level":1}
result = collection.insert_one(data)
print(result.inserted_id)
documents = collection.find()
pd.DataFrame(list(documents)).tail(3)
# 여러개의 데이터 저장 - insert_many
data = [
{"subject":"java", "level":1, "comments":[{"name":"peter", "msg":"easy"}]},
{"subject":"html", "level":2, "comments":[{"name":"peter", "msg":"medium"}]},
{"subject":"gulp", "level":3, "comments":[{"name":"peter", "msg":"hard"}]},
]
result = collection.insert_many(data)
print(result.inserted_ids)
# limit 데이터 갯수 제한
documents = collection.find().limit(3)
pd.DataFrame(list(documents))
ex) 직방 원룸 데이터 수집해서 데이터베이스에 저장하기
# !pip install geohash2
import zigbang as zb
data = zb.oneroom('망원동')
data.tail(2)
data.to_dict('records')[0]
db = client.zigbang # zigbang database
collection = db.oneroom # oneroom collection
result = collection.insert_many(data.to_dict('records'))
len(result.inserted_ids)
# 저장된 데이터 읽어오기
data = collection.find()
df = pd.DataFrame(list(data))
df.tail(2)
# deposit : 1000 이하, rent : 100 이하, size_m2: 30 이상, floor: 반지하 아님manage_cost : 오름차
query = {'deposit': {'$lte': 1000}, 'rent': {'$lte': 100}, 'size_m2': {'$gte': 30}, 'floor': {'$
documents = collection.find(query).sort("manage_cost", pymongo.DESCENDING)
df1 = pd.DataFrame(list(documents))
df1
UPDATE Document
db = client.mongo
collection = db.info
documents = collection.find({'subject': 'html'})
pd.DataFrame(list(documents))
query = {'subject': 'html'}
update = {'$set': {'level': 3}}
collection.update_one(query, update)
documents = collection.find({'subject': 'html'})
pd.DataFrame(list(documents))
query = {'subject': 'html'}
update = {'$set': {'level': 1}}
collection.update_many(query, update)
query = {'subject': 'html'}
update = {'$set': {'level': 1}}
collection.update_many(query, update)
documents = collection.find({'subject': 'html'})
pd.DataFrame(list(documents))
DELETE Document
# level 1 데이터 삭제
documents = collection.find()
pd.DataFrame(list(documents))
# level 1 데이터 삭제
query = {'level': {'$eq': 1}}
collection.delete_many(query)
documents = collection.find()
pd.DataFrame(list(documents))
데코레이터 파이썬문법
'KT AIVLE School 3기 > AIVLER 활동' 카테고리의 다른 글
[AIVLE_AI] SQL 2일차 (0) | 2023.05.08 |
---|---|
[AIVLE_AI] SQL 1일차 (0) | 2023.05.08 |
[AIVLE_AI] WEB/WAS/DB 1일차 (0) | 2023.05.08 |
[AIVLE_AI] 웹 프로그래밍 2일차 (0) | 2023.05.08 |
[AIVLE_AI] 웹 프로그래밍 1일차 (0) | 2023.05.08 |