티스토리 뷰

MongoDB는 Collection에 데이터를 생성, 조회, 삭제, 수정할 수 있는 명령어를 지원하고 JavaScript처럼 변수에 데이터를 할당해서 저장할 수 있다.

 

먼저 insert에 대해 다뤄보자. insert 명령어는 3가지를 제공한다.

insert - 단일 or 다중의 Document를 생성
insertOne - 단일 Document를 생성
insertMany - 다중의 Document를 생성

Collection 데이터 저장하기

object = {"name":"kimjonghyun", "age":28}
db.developers.insert(object)
db.developers.find()

object 변수에 이름과 나이를 저장 후 insert함수 인자로 넘겨 insert를 실행하고 조회한 결과다.
MongoDB에서는 insert를 수행하면 _id라는 ObjectId 타입의 고유값을 부여한다. ObjectId 타입에 대해서는 여기를 참고하자.



array = [{"name":"abc", "age":10}, {"name":"def", "age":20}]
db.developers.insertMany(array)
db.developers.find()

insertMany를 사용하면 Array 타입의 변수를 insertMany함수 인자로 넘겨 처리할 수 있다.

Collection 데이터 수정하기

db.developers.updateOne({"name":"kimjonghyun"}, { $set : {"skills":["JAVA", "Spring"]} })
db.developers.find()

update도 마찬가지로 updateOne과 updateMany도 지원해준다. 위 명령어는 name이 kimjonghyun인 Document의 skills 라는 필드에 Array Field를 update하는 명령어이다.MongoDB는 Schemaless하는 장점이 있어서 insert나 update를 할 때 원하는 Field명도 마음대로 넣을 수 있다.



db.developers.updateMany({"age" : { $lte : 20 }}, { $set : {"skills":["JSP"]} })
db.developers.find()

위 명령어는 age가 20보다 같거나 작은 Document들의 skills를 Array Field로 update하고 Array요소에 문자열 1개를 넣는다.

Collection에 데이터 조회하기

db.developers.find();
db.developers.findOne();

MongoDB에서는 find()나 findOne() 두개의 명령어로 Document를 조회할 수 있다. findOne를 실행하면 Document에서 가장 첫번째의 값 1개를 가져온다.



db.developers.find({})
db.developers.find({"age" : { $lte : 20 }})

find(), findOne() 함수의 첫번째 인자엔 filter조건이 들어가는데 filter할 데이터가 없으면 {}라고 넣어주면 된다.

MongoDB 비교연산자

$eq : 주어진 값과 일치하는 값
$ne : 주어진 값과 일치하지 않는 값
$lt : 주어진 값보다 작은 값
$lte : 주어진 값보다 같거나 작은 값
$gt : 주어진 값보다 큰 값
$gte : 주어진 값보다 같거나 큰 값
$in : 주어진 배열안에 존재하는 값
$nin : 주어진 배열안에 존재하지 않는 값

MongoDB 논리연산자

$or : 주어진 조건중 하나라도 true일 때 true
$and : 주어진 모든조건이 true일 때 true
$not : 주어진 조건이 false일 때 true
$nor : 주어진 모든조건이 false일 때 true

MongoDB 비교/논리연산자를 활용한 몇가지 예제작성

db.developers.find({"name": { $eq : "kimjonghyun" }})

name이 kimjonghyun인 Document를 조회



db.developers.find({"age" : { $ne : 20 }})

age가 20이 아닌 Document를 조회



db.developers.find({"skills" : { $in:["JSP"] }})

skills중에서 'JSP'가 존재하는 Document를 조회



db.developers.find({"skills.1" : { $eq : "Spring"}})

skills중에서 index 1번요소가 'Spring'인 Document를 조회



db.developers.find({ $or : [{"age" : { $ne : 10 }}, {"name" : { $eq : "abc" }}] })

age가 10이 아니거나 name이 abc인 Document를 조회



db.developers.find({ $and : [{"skills.1" : { $eq : "Spring"}}, {"age" : { $eq : 28 }}] });

skills index 1번요소가 Spring 이면서 age가 28인 Document를 조회

Collection에서 특정 필드만 조회하기

db.developers.find({}, {"name": true})

developers Document에서 name 필드만 조회하기.



db.developers.find({}, {"age": false})

developers Document에서 age 필드를 제외한 나머지 필드 조회하기.

Collection에 데이터 삭제하기

db.developers.deleteOne({"skills" : { $in:["JSP"] }})

developers Document의 skills필드중에 JSP가 존재하는 첫번째 Document를 삭제하기



db.developers.deleteMany({"age" : { $gte : 20 }})

developers Document에서 age 필드가 20보다 큰 Document들을 삭제하기.


추가로 더 알게된 내용들은 최신화 해둘 예정입니다.

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함