Server/Database

몽고디비(MongoDB) 사용법 - document(레코드) 관련

juhpark 2024. 11. 9. 23:42

몽고디비의  레코드는  document로 저장이 된다.

document 추가하기

db.[Collection명].insert({JSON데이터}) # 한건 입력
db.[Collection명].insert([{JSON데이터}, ...]) # 여러건 입력

 

document 전체 조회하기

db.[Collection명].find()     # 전체조회하기

 

document  조건으로 조회하기

db.[Collection명].find({조건})
ex) db.[Collection명].find({color: 'white'})
db.[Collection명].findOne({조건}) # 조건에 맞는 한건만 조회

 

document 출력 항목 선택하기

db.[Collection명].find({조건}, {Projection}) # 출력항목을 Projection이라 함
ex) db.[Collection명].find({color: 'white'},{color: 1})
# 두번째 인자의 항목의 값이 1인 경우, 출력 0인 경우 출력하지 않음

 

document 업데이트

# color가 white인 한 건을 blue로 바꾸는 예제
db.[Collection명].updateOne({color: 'white'}, {$set: {color: 'blue'}})
# color가 white인 모든 건을 blue로 바꾸는 예제
db.[Collection명].updateMany({color: 'white'}, {$set: {color: 'blue'}})

 

document 삭제

db.[Collection명].remove({}) # 전체 document 삭제
db.[Collection명].remove({color: 'white'}) # 조건에 맞는 document 삭제
db.[Collection명].deleteOne({color: 'white'}) # 조건에 맞는 document 한건 삭제
db.[Collection명].deleteMany({color: 'white'}) # 조건에 맞는 document 전체 삭제
반응형