Query Selectors
쿼리 셀렉터
비교 연산자
$eq
- 지정된 값과 같은 값을 조회
- 형식
{ <field>: { $eq: <value> } }
- value로 정규식이 오는 경우를 제외하고 아래 형식과 결과가 동일
{ field: <value> }
- $eq에 value로 정규식을 사용하면 정규식인 개체를 찾아 반환
// company 가 문자열 값을 저장 중이라면 일치하는 값이 없어 반환 결과가 없음
db.collection.find( { company: { $eq: /MongoDB/ } }, {_id: 0 } )
$gt
- 지정된 값보다 큰 값을 조회(초과)
- 형식
{field: {$gt: value} }
$gte
- 지정된 값보다 크거나 같은 값을 조회(이상)
- 형식
{field: {$gte: value} }
$in
- 배열에 지정된 값 중 하나에 해당되는 값들을 조회
- 형식
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
$lt
- 지정된 값보다 작은 값을 조회(미만)
- 형식
{field: {$lt: value} }
$lte
- 지정된 값보다 작거나 같은 값을 조회(이하)
- 형식
{ field: { $lte: value} }
$ne
- 지정된 값과 같지 않은 모든 값을 조회
- 형식
{field: {$ne: value} }
- 단독 사용 시 index 의 일치하는 경우가 많기 때문에 호율이 안좋음
$nin
- 배열에 지정된 값과 일치하지 않는 값을 조회
- 형식
{ field: { $nin: [ <value1>, <value2> ... <valueN> ]} }
- 단독 사용 시 index 의 일치하는 경우가 많기 때문에 호율이 안좋음
논리 연산자
$and
- 하나 이상의 표현식의 배열에 대해 모든 표현식을 충족하는 문서를 반환
- 형식
{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
$not
- 쿼리의 효과를 반전하고 쿼리 식과 일치 하지 않는 문서를 반환
- 형식
{ field: { $not: { <operator-expression> } } }
$nor
- 하나 이상의 표현식의 배열에 대해 논리 연산을 수행하고 배열의 모든 쿼리 식에 해당하지 않는 문서를 반환
- 형식
{ $nor: [ { <expression1> }, { <expression2> }, ... { <expressionN> } ] }
$or
- 하나 이상의 표현식의 배열에 대해 적어도 하나의 표현식을 충족하는 문서를 반환
- $in은 하나의 필드의 값에 대해 비교(비교 기준이 다름)
- 형식
{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
요소 쿼리
$exists
- 지정된 필드의 유무에 대해 지정
- 형식
{ field: { $exists: <boolean> } }
$type
- 필드가 지정된 Type과 일치하는 문서를 선택
- Array 값 중 하나에 해당하는 문서를 선택
- 형식
{ field: { $type: <BSON type> } }
{ field: { $type: [ <BSON type1> , <BSON type2>, ... ] } }
평가 쿼리
$expr
- 쿼리 언어 내에서 집계 표현식을 사용
- 형식
{ $expr: { <expression> } }
- 예시
// 데이터
{ "_id" : 1, "category" : "food", "budget": 400, "spent": 450 }
{ "_id" : 2, "category" : "drinks", "budget": 100, "spent": 150 }
{ "_id" : 3, "category" : "clothes", "budget": 100, "spent": 50 }
{ "_id" : 4, "category" : "misc", "budget": 500, "spent": 300 }
{ "_id" : 5, "category" : "travel", "budget": 200, "spent": 650 }
// 쿼리 실행
db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )
// 결과 - spent이 budget보다 큰 도큐먼트 반환
{ "_id" : 1, "category" : "food", "budget" : 400, "spent" : 450 }
{ "_id" : 2, "category" : "drinks", "budget" : 100, "spent" : 150 }
{ "_id" : 5, "category" : "travel", "budget" : 200, "spent" : 650 }
$jsonSchema
- 주어진 JSON 스키마에 대해 문서의 유효성을 검사
- 형식
{ $jsonSchema: <JSON Schema object> }
- 스키마 유효성 검사: 삽입 및 업데이트 작업에 유효성 검사
- 쿼리 조건: 지정된 스키마를 만족 컬렉션의 문서를 조회 및 읽기, 쓰기 작업
$mod
- 나머지를 구하는 쿼리
- 형식
{ field: { $mod: [ divisor, remainder ] } }
- 예시
// 4로 나누고 나머지가 0인 문서 반환
db.inventory.find( { qty: { $mod: [ 4, 0 ] } } )
$regex
- 값이 지정된 정규식과 일치하는 문서를 선택
- 형식
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
$text
- 텍스트 인덱스로 인덱싱된 필드의 내용에 대해 텍스트 검색을 수행
- 형식
{
$text:
{
$search: <string>,
$language: <string>,
$caseSensitive: <boolean>,
$diacriticSensitive: <boolean>
}
}
- 예시
// 컬렉션 생성
db.articles.createIndex( { subject: "text" } )
// 도큐먼트 추가
db.articles.insert(
[
{ _id: 1, subject: "coffee", author: "xyz", views: 50 },
{ _id: 2, subject: "Coffee Shopping", author: "efg", views: 5 },
{ _id: 3, subject: "Baking a cake", author: "abc", views: 90 },
{ _id: 4, subject: "baking", author: "xyz", views: 100 },
{ _id: 5, subject: "Café Con Leche", author: "abc", views: 200 },
{ _id: 6, subject: "Сырники", author: "jkl", views: 80 },
{ _id: 7, subject: "coffee and cream", author: "efg", views: 10 },
{ _id: 8, subject: "Cafe con Leche", author: "xyz", views: 10 }
]
)
// 한 단어 검색
db.articles.find( { $text: { $search: "coffee" } } )
// 한 던어 검색 결과
{ "_id" : 2, "subject" : "Coffee Shopping", "author" : "efg", "views" : 5 }
{ "_id" : 7, "subject" : "coffee and cream", "author" : "efg", "views" : 10 }
{ "_id" : 1, "subject" : "coffee", "author" : "xyz", "views" : 50 }
// 모든 검색어와 일치
db.articles.find( { $text: { $search: "bake coffee cake" } } )
// 모든 검색어와 일치 결과
{ "_id" : 2, "subject" : "Coffee Shopping", "author" : "efg", "views" : 5 }
{ "_id" : 7, "subject" : "coffee and cream", "author" : "efg", "views" : 10 }
{ "_id" : 1, "subject" : "coffee", "author" : "xyz", "views" : 50 }
{ "_id" : 3, "subject" : "Baking a cake", "author" : "abc", "views" : 90 }
{ "_id" : 4, "subject" : "baking", "author" : "xyz", "views" : 100 }
// 구문 검색
db.articles.find( { $text: { $search: "\"coffee shop\"" } } )
// 구문 검색 결과
{ "_id" : 2, "subject" : "Coffee Shopping", "author" : "efg", "views" : 5 }
// 그외 아래 링크 참고
// https://docs.mongodb.com/manual/reference/operator/query/text/
$where
- JavaScript 표현식을 만족하는 문서 조회
- 형식
{ $where: <string|JavaScript Code> }
- 예시
// 도큐먼트 추가
db.players.insertMany([
{ _id: 12378, name: "Steve", username: "steveisawesome", first_login: "2017-01-01" },
{ _id: 2, name: "Anya", username: "anya", first_login: "2001-02-02" }
])
// $where 사용 질의
db.players.find( { $where: function() {
return (hex_md5(this.name) == "9b53e667f30cd329dca1ec9e6a83e994")
} } );
배열
$all
- 쿼리에 지정된 모든 요소를 포함하는 배열과 일치
- 형식
{ <field>: { $all: [ <value1> , <value2> ... ] } }
- 예시
// $and연산과 동일
{ tags: { $all: [ "ssl" , "security" ] } }
{ $and: [ { tags: "ssl" }, { tags: "security" } ] }
// 중첩 배열 - 3개가 동일
db.articles.find( { tags: { $all: [ [ "ssl", "security" ] ] } } )
db.articles.find( { $and: [ { tags: [ "ssl", "security" ] } ] } )
db.articles.find( { tags: [ "ssl", "security" ] } )
$elemMatch
- 배열 필드의 요소가 지정된 모든 조건과 일치하는 경우 문서를 선택
- 형식
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
- 예시
// 도큐먼트 추가
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }
// $elemMatch 사용 질의
db.scores.find(
{ results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)
// 결과
{ "_id" : 1, "results" : [ 82, 85, 88 ] }
$size
- 배열 필드가 지정된 크기인 경우 문서를 선택
- 형식
{ <field>: { $size: value } }
참고 사이트
'dev > DB' 카테고리의 다른 글
| MongoDB - 집계2 (0) | 2021.11.04 |
|---|---|
| MongoDB - 집계1 (0) | 2021.10.28 |
| [MongoDB] 도큐먼트 지향 데이터 (0) | 2021.10.15 |
| 자바스크립트 셸을 통한 MongoDB (0) | 2021.09.30 |
| MongoDB 핵심 기능 요약 (0) | 2021.09.27 |