본문 바로가기
Research/Database

mongoDB Atlas_데이터 다루기(CRUD) 기본

by RIEM 2022. 11. 21.
728x90

CRUD

데이터 삽입, 읽기, 바꾸기, 지우기 코드를 한번에 정리해보자.

Create

# 저장 - 예시 : 'name'키는 'bobby'이고 'age' 키는 21인 데이터 1개를 삽입해줘
doc = {'name':'bobby','age':21}
db.users.insert_one(doc)

Read

# 한 개 찾기 - 예시 : 'name' 키에 'bobby' 값을 가진 데이터 1개를 찾아라
user = db.users.find_one({'name':'bobby'})
# 여러개 찾기 - 예시 ( _id 값은 제외하고 출력해줘). 객체로 반환되는 것을 반복문 돌리기 위해서 list화 시킴
all_users = list(db.users.find({},{'_id':False}))

Update

# 바꾸기 - 예시
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})

Delete

# 지우기 - 예시
db.users.delete_one({'name':'bobby'})

 

mongoDB에 데이터 1개 입력하기 예시

MongoClient의 파라미터인 문자열 내 id, pw 부분은 각자 mongoDB 아틀라스 아이디와 패스워드를 대입하면 된다.

from pymongo import MongoClient
client = MongoClient('mongodb+srv://id:pw@cluster0.5hnlvb6.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta

doc = {
    'name': 'bob',
    'age' : 27
}

# Please insert 'doc' data in 'users' data collection inside the db system
db.users.insert_one(doc)

데이터가 정상적으로 들어간 것을 알 수 있다. id값은 프라이머리 키기 때문에 자동으로 생기는 것 같다.

활용하기

# Get '가버나움''s star scores
movie = db.movies.find_one({'title':'가버나움'})['star']
print(movie)

# get all movies with same star scores that '가버나움' has
results = list(db.movies.find({'star':movie}, {'_id':False}))
for result in results:
    print(result)

# Change '가버나움's score to '0'
db.movies.update_one({'title':'가버나움'},{'$set':{'star':'0'}})
print(movie)
728x90

댓글