2023. 9. 21. 11:27ㆍdata engineer/database
⚙️ 실행환경
- OS: Silicom Mac (m1)
- IDE: Pycharm
✔️ 목차
1. Basic
2. find/ insert/ update/ delete/aggregate 관련 모듈
3. json 데이터를 이용한 geo spatial 사용
1️⃣ Basic
MongoDB란 NoSQL로 비정형 데이터를 분산 저장하고 유연한 데이터 스키마를 갖는 특징이 있다.
Pymongo는 python으로 몽고db를 다루기 위해 사용하는 패키지이다.
MongoClient(ip, port)는 ip와 port를 파라미터로 갖고, client를 지정한다.
과정을 요약하자면
mongo client 클래스 객체 할당 >> db객체 할당 >> collection 객체 할당
아래 코드에서는 'test' db에서 'multi' collection 객체를 할당받았다.
from pymongo import MongoClient
# MongoClient(ip, port)
#client = MongoClient("localhost",27017)
client = MongoClient("mongodb://localhost:27017")
#db = client.test
db=client['test']
#collection = db.multi
collection = db['multi']
documents = collection.find()
print(documents)
for doc in documents:
print(doc)
결과
<pymongo.cursor.Cursor object at 0x7fe320323490>
{'_id': ObjectId('64eed7256648465134d76985'), 'name': 'hong-gd', 'kor': 65, 'eng': 60, 'math': 100}
{'_id': ObjectId('64eed7256648465134d76986'), 'name': 'kim-sd', 'kor': 100, 'eng': 100, 'math': 40}
{'_id': ObjectId('64eed7256648465134d76987'), 'name': 'you-js', 'kor': 96, 'eng': 40, 'math': 100}
첫번째 print(documents)의 결과
- <pymongo.cursor.Cursor object at 0x7f8568397af0> cursor 객체로 메모리 주소 정보 포함
- cursor는 query 요청시 나오는 result set에 향한 포인터로
- Cursor 객체를 반복하면 db result set 문서에 접근 가능
두번째 print(doc)의 결과
- multi collection에 있는 내용을 모두 출력함
2️⃣ Find
find() : cursor 객체만 나옴
find_one() : 특정 document 바로 출력됨
count_documents() : documents 수 출력
from pymongo import MongoClient
from pprint import pprint
client = MongoClient("localhost", 27017)
db = client.test
score = db.score
cursor = score.find()
for doc in cursor:
pprint(doc)
print("-----------------")
#find(): cursor 객체 출력
lee = score.find({"name":"이순신"})
pprint(lee)
for doc in lee:
pprint(doc)
print("-----------------")
#find_one: doc 출력
hong = score.find_one({"name":"홍길동"})
pprint(hong)
print("-----------------")
print(score.count_documents({}))
#국어점수 75이상인 doc 출력
kor = score.find({"kor":{"$gte": 75}})
for doc in kor:
print(doc)
3️⃣ insert
insert_many() : 여러개의 값 한번에 넣기
inserted_ids : 추가된 id들 확인
insert_one() : 하나의 doc만 추가
inserted_id : 추가된 하나의 id 확인
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client['test']
score = db['score']
members = [
{"name": "이강인",
"midterm": {"kor":100, "eng":100, "math":100},
"final": {"kor":100, "eng":100, "math":100}},
{"name": "손흥민",
"midterm": {"kor": 100, "eng": 100, "math": 100},
"final": {"kor": 100, "eng": 100, "math": 100}}
]
result01 = score.insert_many(members)
print(result01.inserted_ids)
> [ObjectId('64efefa9e347250fb8e8357b'), ObjectId('64efefa9e347250fb8e8357c')]
result02 = score.insert_one({"name": "김민재", "kor":100, "eng":100, "math":100})
print(result02.inserted_id)
4️⃣ Update
update_one() : 매칭되는 내용이 한개일 때
update_many() : 매칭되는 내용이 한개일 때
matched_count : 매치(해당하는) 내용 수
modified_count : 수정내용 수
from pymongo import MongoClient
client = MongoClient("localhost", 27017)
db = client.test
score = db.score
result01 = score.update_one({"name":"황희찬"}, {"$set": {"math":50}})
print(result01.matched_count)
print(result01.modified_count)
result02 = score.update_many({"midterm.eng": {"$eq": 100}}, {"$set": {"midterm.eng":0}})
print(result02.matched_count)
print(result02.modified_count)
5️⃣ Delete
delete_one : 하나의 값 삭제
delete_many : 여러개의 값 삭제
deleted_count : 삭제된 값의 갯수
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client['test']
score = db['score']
result01 = score.delete_one({"name":"김민재"})
print(result01.deleted_count)
delete_many
6️⃣ aggregate
aggregate([{match}, {project}, {group}])
- match : 검색조건 (where와 유사)
- project : 원하는 변수명 (select와 유사)
- group : 가져올 값 (groupby, 집계 파이프라인)
#db와 collection 한번에 쓰는 법
# 방법1
score = client.test.score
# 방법2
db = db.client.test
result = db.score.aggregate()
result = score.aggregate([
{"$match": {"kor": {"$gte": 50}}},
{"$group": }
])
for doc in result:
print(doc)
print(result)
print(list(result))
#이렇게 해도 결과 나옴
'data engineer > database' 카테고리의 다른 글
[de]Bigquery:기본정보와 문법 (0) | 2024.03.07 |
---|---|
[de]Bigquery: 구글서치콘솔 데이터 확인 (0) | 2024.03.01 |
[de]Bigquery (0) | 2024.02.29 |
[de] Oracle (1/3) (0) | 2023.09.21 |
[de] Pymongo (1/2) (0) | 2023.08.31 |