Database/NoSQL

[MongoDB] PyMongo(python 라이브러리)로 MongoDB사용하기

Ella_K 2022. 7. 21. 23:33

🔥 PyMongo, dnspython 설치

'pip install pymongo' , 'pip install dnspython'

 

🔥 DB 연결

👉 MongoDB Atlas 사용하기

  • MongoDB Atlas는 무료 클라우드를 제공해준다.
  • MongoDB Atlas 클러스터 생성은 ' 무료 몽고디비 Atlas ' 참고
  • DB 연결을 위해 아래 코드를 추가한다.
from pymongo import MongoClient
client = MongoClient('mongodb+srv://test:<password>a@cluster0.mndqybx.mongodb.net/myFirstDatabase?retryWrites=true&w=majority')
클러스터 연결하면서 'connection stirng' 을 복사하라고 나온다. 
그 connection string을 MongoClient안에 넣으면 된다.
여기서 connection string의 test, <password>, myFirstDatabase를 아래와 같이 대체해야한다.
test : database user 생성할 때 적은 user name
<password> : user name과 같이 적은 password
myFirstDatabase : cluster 생성할 때 적은 cluster name

 

👉 DB 생성

db = client.mydb

서버에 mydb라는 database가 생성된다.

 

🔥 데이터 다루기

👉 저장

doc = {'name':'amy','age':25} # 데이터 하나
db.users.insert_one(doc)

'users' 이름의 collection이 생성되고, 'users' collection에 doc 딕셔너리가 저장된다.

 

👉 찾기

  • 한 개 찾기
user = db.users.find_one({'name':'amy'})
print(user) 
# {'_id': ObjectId('62d960bdff897dba99afecff'), 'name': 'amy', 'age': 25}

user = db.users.find_one({'name':'amy'},{'_id':False})
print(user)
# {'name': 'amy', 'age': 25}

{ } 안에는 조건이 들어간다. 'name'의 value가 'amy'인 데이터(dictionary)를 찾는다.
{'_id' : False} 라는 조건을 걸어주면 id값은 불러오지 않는다.

 

  • 여러개 찾기
all_users = list(db.users.find({},{'_id':False}))
# [{'name': 'amy', 'age': 25}, {'name': 'bobby', 'age': 21}, {'name': 'tom', 'age': 21}]


all_users = list(db.users.find({'age': 21},{'_id':False}))
# [{'name': 'bobby', 'age': 21}, {'name': 'tom', 'age': 21}]

{ }가 비워있으면 users콜렉션에 저장된 모든 데이터(dictionary)를 가져오고, 
{ }안에 조건이 있으면, 조건에 해당되는 모든 데이터(dictionary)를 가져온다.

 

👉 바꾸기

db.users.update_one({'name':'amy'},{'$set':{'age':19}})

'name'의 value가 'amy'인 데이터(dictionary)를 찾아서 'age'의 value를 19로 바꾼다.

 

👉 지우기 

db.users.delete_one({'name':'amy'})

'name'의 value가 'amy'인 데이터(dictionary)를 찾아서 삭제한다.

 


Source

 

스파르타코딩클럽 [웹개발 종합반]

5주안에 빠르게 배우고, 내것을 만드세요! 코딩을 전혀 모르는 왕초보 대상의 웹개발 입문 강의.

spartacodingclub.kr

 

What is MongoDB Atlas? — MongoDB Atlas

MongoDB Atlas is a multi-cloud database service by the same people that build MongoDB. Atlas simplifies deploying and managing your databases while offering the versatility you need to build resilient and performant global applications on the cloud provide

www.mongodb.com

 

[MongoDB] 무료 몽고디비(MongoDB) Atlas

MongoDB Atlas 란? MongoDB Atlas는 MongoDB를 설계한 사람들이 만든 모든 것을 관리하는 클라우드 데이터베이스 AWS, Azure, GCP를 통해 배포에 관한 모든 것을 통합 관리해줌  -위키백과- - MongoDB를 설치하면.

dev-cini.tistory.com

 

Python으로 MongoDB 이용하기 01

PyMongo Tutorial

wooiljeong.github.io

 

'Database > NoSQL' 카테고리의 다른 글

[Redis] 레디스 영속성 (Redis persistence)  (0) 2022.12.04