Loading...

DB/MongoDB / / 2022. 5. 2. 15:11

몽고DB 8강. 배열 연산자

반응형

 

use("blog")

db.food.insertOne({_id:1, fruit: ["apple", "banana", "peach"]});
db.food.insertOne({_id:2, fruit: ["apple", "kumquat", "orange"]});
db.food.insertOne({_id:3, fruit: ["cherry", "banana", "apple"]});
db.food.insertOne({_id:4, fruit: ["cherry", "raspberry", "peach"]});

 

몽고 디비에서 _id가 PK이다.

id가 1인것을 찾는 것은 어렵지 않다.

 

db.food.find({_id:1})

 

fruit에 banana를 들고 있는 사람이 있는지 물어보는 건 다르다.

 

배열의 순서도 같아야하고, 가지고 있는 요소가 완전히 같아야 찾을 수 있다.

배열을 검색하는 방법이 따로있다.

 

1. $all 포함하고 있는가?

db.food.find({fruit: {$all : ["apple"]}});
db.food.find({fruit: {$all : ["apple", "banana"]}});

순서에 상관없이 둘 다 가지고 있는 도큐먼트를 찾는다.

 

2. $in

db.food.find({fruit: {$in : ["apple", "banana"]}});

둘 중에 하나라도 포함하고 있는 도큐먼트를 찾는다.

 

3. $size

db.food.find({fruit: {$size:3}});

 

4. $push 배열에 값 추가

db.food.updateOne({_id:2}, {$push : {fruit: "raspberry"}});
db.food.find({_id:2});

 

 

5. $pull 배열에 값 제거

db.food.updateOne({_id:2}, {$pull : {fruit: "raspberry"}});
db.food.find({_id:2});

 


6. 배열 내부의 전체 도큐먼트 갱신하기

db.post.insertOne({_id:1, replys : [
    {id:1, content:"내용1", userId: 1},
    {id:2, content:"내용2", userId: 1},
    {id:3, content:"내용3", userId: 2},
]});
db.post.insertOne({_id:2, replys : [
    {id:4, content:"내용4", userId: 1},
    {id:5, content:"내용5", userId: 1},
    {id:6, content:"내용6", userId: 2},
]});

 

댓글의 아이디가 4인 것을 찾으면 해당 댓글이 포함된 도큐먼트 전체를 리턴해준다.

db.post.find({"replys.id":4});

 

배열 내부를 검색해보자.

userId가 1이면서 replys의 id가 4인 배열 요소를 찾아보자.

 

$elemMatch 우선 첫 번째로 해당 요소를 찾은 다음 그 요소를 가지고 있는 도큐먼트를 뱉어낸다.

db.post.find(
  {replys: {$elemMatch: {id:4, userId:1}}}
);

 

전체 도큐먼트에서 내가 원하는 요소만 뱉기 위해서는

첫 번째 매개변수에서 연산한 결과의 파이프라인을 타고 나와서

reply.$ = true를 하면 해당 요소의 위치를 뱉어준다.

해당 요소만 잘 찾아낸다.

db.post.find(
  {
    replys: {$elemMatch: {id:4, userId:1}}
  },
  {"replys.$":1}
);

 

$elemMatch는 배열 내부 문서의 여러 가지 필드를 검색할 수 있고,

$ 연산자는 찾은 위치를 뱉어내는 것이다.

"replys.$" : 1인 것은 첫 번째 요소를 뱉어낸다는 말이다.

 

이 정도만 알고 넘어가자.

 

 

[출처]

 

https://cafe.naver.com/metacoding

 

메타코딩 : 네이버 카페

코린이들의 궁금증

cafe.naver.com

메타 코딩 유튜브

https://www.youtube.com/c/%EB%A9%94%ED%83%80%EC%BD%94%EB%94%A9

 

메타코딩

문의사항 : getinthere@naver.com 인스타그램 : https://www.instagram.com/meta4pm 깃헙 : https://github.com/codingspecialist 유료강좌 : https://www.easyupclass.com

www.youtube.com

 
반응형