티스토리 뷰

Backend/꾸준히 TIL

[mongodb] $in 와 $exist operator

개발하는 후딘 2022. 8. 29. 14:02
728x90
반응형

[참고자료]

 

$in — MongoDB Manual

Docs Home → MongoDB Manual $inThe $in operator selects the documents where the value of a field equals any value in the specified array. To specify an $in expression, use the following prototype:{ field: { $in: [ , , ... ] } }For comparison of different

www.mongodb.com

 

 

$exists — MongoDB Manual

Docs Home → MongoDB Manual $existsSyntax: { field: { $exists: } }When is true, $exists matches the documents that contain the field, including documents where the field value is null. If is false, the query returns only the documents that do not contain

www.mongodb.com

 

 

01.MongoDB 기초 - CRUD 문법

🌈 CRUD 문법 > ### 🔥 생성(Create) - Insert > ### 🔥 읽기(Read) - Search > ### 🔥 수정(Updata) - Update > ### 🔥 삭제(Delete) - Drop 1. 생성(Create) - Insert 데이

velog.io


[ $in ]

{ field: { $in : [ <val1>, <val2>, ... , <valN> ] }}

해당 field에서 <val1>, <val2>, ... , <valN> 값이 들어있는지 확인하여

해당필드가 배열원소가 하나라도 갖고있다면, 해당 다큐먼트들로만 추려냅니다.

 

(예시)

insertMany라는 콜렉션이 있습니다.

db.inventory.insertMany( [
   { "item": "Pens", "quantity": 350, "tags": [ "school", "office" ] },
   { "item": "Erasers", "quantity": 15, "tags": [ "school", "home" ] },
   { "item": "Maps", "tags": [ "office", "storage" ] },
   { "item": "Books", "quantity": 5, "tags": [ "school", "storage", "home" ] }
] )

 

quantity 필드 중 5 나 15 값을 가진  다큐먼트들을 추려냅니다.

* { _id: 0 } _id를 제외하고 일부키를 가져오도록하는 옵션입니다.

db.inventory.find( { quantity: { $in: [ 5, 15 ] } }, { _id: 0 } )

 

 

find 함수에 $in 옵션을 추가하여 조건에 부합하는 결과입니다.

{ item: 'Erasers', quantity: 15, tags: [ 'school', 'home' ] },
{ item: 'Books', quantity: 5, tags: [ 'school', 'storage', 'home' ] }

 


[ $exist ]

{ field: { $exist: true/false } }

해당 field 의 존재유무를 따집니다.

해당 field가 존재하는 다큐먼트(data-row)를 구하고싶다면, $exist: true 로 설정합니다.

반대로 field가 존재하지 않는 다큐먼트(data-row)를 구하고싶다면, $exist: false 로 설정합니다.

조건에 만족하는 데이터만 추려내는 filter 와 같은 역할을 합니다.

 

(예시)

records 콜렉션에 아래와 같이 10개의 다큐먼트가 존재한다고 가정합니다.

{ a: 5, b: 5, c: null }
{ a: 3, b: null, c: 8 }
{ a: null, b: 3, c: 9 }
{ a: 1, b: 2, c: 3 }
{ a: 2, c: 5 }
{ a: 3, b: 2 }
{ a: 4 }
{ b: 2, c: 4 }
{ b: 2 }
{ c: 6 }

 

records 콜렉션 안에서 a 필드에 값이 있고, a필드가 존재하는 다큐먼트만을 구합니다.

db.records.find( { a: { $exists: true } } )

 

몽고디비 find에서 exist 옵션을 추가해서 조건에 맞는 다큐먼트들로 필터링된 결과입니다.

{ a: 5, b: 5, c: null }
{ a: 3, b: null, c: 8 }
{ a: null, b: 3, c: 9 }
{ a: 1, b: 2, c: 3 }
{ a: 2, c: 5 }
{ a: 3, b: 2 }
{ a: 4 }

 

728x90
반응형

'Backend > 꾸준히 TIL' 카테고리의 다른 글

[mongodb/mongoose] __v 필드  (0) 2022.08.31
bcrypt 설치 관련 에러  (0) 2022.08.29
vscode prettier 적용하기  (2) 2022.08.29
[mongodb/mongoose] methods vs method  (0) 2022.08.28
[mongodb] _id 컬럼으로 검색 - find()/findOne()  (0) 2022.08.28
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 31
글 보관함