Database/MongoDB

[몽고DB 완벽 가이드] 4. 쿼리

noahkim_ 2025. 4. 28. 14:49

크리스티나 초도로 , 섀넌 브래드쇼 , 오언 브라질 님의 "몽고DB 완벽 가이드" 책을 정리한 포스팅 입니다.

 

1. find()

필터

  • 첫 매개변수를 필터로 사용함
  • 전체 조회 시 빈 도큐먼트 전달
  • 여러 키-값 쌍을 전달할 수 있음 (AND)

 

예제

더보기
db.pageviews.find({})
db.pageviews.find({pageviews: 1})
db.pageviews.find({pageviews: 1, url: "www.example.org"})

 

반환받을 키 지정

  • 두번째 매개변수를 사용함
  • 반환 받고싶은 키를 프로젝션할 수 있음 (1)
  • 반환을 제외할 키를 프로젝션할 수 있음 (0)

 

예제

더보기
db.pageviews.find({url: "www.example.com"}, {_id: 1}) # _id 만 출력
db.pageviews.find({url: "www.example.com"}, {_id: 0}) # _id 만 제외 (나머지 출력)

# id 출력, comments 제외 -> comments를 제외한 나머지 모두 출력됨 (id만 섞어쓰기 가능)
db.pageviews.find({url: "www.example.com"}, {_id: 1, comments: 0})

 

제약 사항

  • 쿼리 도큐먼트 값은 반드시 상수여야 함

 

예제

더보기
db.pageviews.find({url: this.suburl}) # ❌

 

2. 쿼리 조건

비교 연산자

연산자 의미 설명
$lt < (less than) 필드 값이 보다 작은 경우
$lte <= (less than or equal) 필드 값이 작거나 같은 경우
$gt > (greater than) 필드 값이 보다 큰 경우
$gte >= (greater than or equal) 필드 값이 크거나 같은 경우
$ne != (not equal)
필드 값이 같지 않은 경우

 

예제

더보기
db.users.find({age: {$gt: 36}})
db.users.find({age: {$gt: 36, $lt: 40}})
db.users.find({start_date: {$lt: new Date("2003-12-01")}})

db.users.find({name: {$ne: "james"}})

 

OR

연산자 설명
$in 필드 값이 주어진 배열 안에 하나라도 일치하면 문서 반환
$nin 필드 값이 주어진 배열 안에 모두 일치하지 않으면 문서 반환
$or 여러 조건 중 하나라도 만족하는 문서 반환

 

예제

더보기
db.users.find({name: {$in: ["james", "curry"]}})
db.users.find({name: {$nin: ["james", "doncic"]}})

db.users.find({$or: [{age: {$gte: 38}}, {start_date: {$lt: new Date("2005-01-01")}}]})

 

$not

  • 주어진 패턴과 일치하지 않는 도큐먼트 검색

 

예제

더보기
db.users.find({age: {$not: {$mod: [5, 1]}}})

 

3. 형 특정 쿼리

구분 설명
null
존재하지 않음
- {field: null}은 값이 null이거나 필드가 아예 없는 경우 매칭
regexp
정규 표현식 매칭
- PCRE: Perl Compatible Regular Expressions 사용 가능
array
배열 관련 연산자 사용
- $all: 배열이 모든 조건을 만족하는지 검사
- $size: 배열 크기 검사
- $slice: 배열 일부만 조회
- $elemMatch: 배열 내부 요소를 조건으로 매칭
nested - $elemMatch: 중첩된 배열 또는 객체 내부를 조건으로 매칭

 

 

예제

더보기

null

# position인 key가 없는 모든 도큐먼트 반환
db.users.find({position: null})

# 값이 null인 키 필터링 ($exists 조건절을 사용하기)
db.users.find({position: {$eq: null, $exists: true}})

 

regex

db.users.find({name: {$regex: /curry/i}})

 

array

db.users.find({nickname: {$all: ["chef", "assasin"]}}) # 전체 포함
db.users.find({nickname: {$size: 2}}) # 배열 개수
db.users.find({name: "curry"}, { nickname: {$slice: -3}}) # 출력할 배열 갯수 조절
db.users.find({"skills.name": "shooting"}) # 내장 도큐먼트 쿼리
db.users.find({"skills.name": "shooting"}, {skills: {$elemMatch: {name: "shooting"}}}) # 내장 도큐먼트 요소 출력

 

4. $where 쿼리

항목 설명
$where (비추천) JavaScript 표현식을 이용해 문서 필터링
- 느리고 위험
$expr
MongoDB 연산자 기반으로 필드 간 비교 등을 수행

 

예시

더보기
db.users.find({$where: "this.age > 25"})
db.users.find({$expr: {$gt: ["$age", 25]}})

 

5. cursor

메서드 설명
limit(n) 결과를 최대 n개까지만 가져오기
skip(n) 처음 n개 결과를 건너뛰고 그 이후부터 가져오기
sort({필드: 1 or -1}) 결과를 필드 기준으로 정렬 (1: 오름차순, -1: 내림차순)

 

예시

더보기
db.users.find().limit(2)
db.users.find().skip(1).limit(1)
db.users.find().sort({age: 1})