요약
- 특정 필드 값을 가지는 document를 모두 가져오고 싶을 때 $eq를 사용
- 특정 필드 값을 가지는 document를 빼고 모두 가져오고 싶을 때 $ne를 사용
{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] }
{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] }
{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] }
{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] }
{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }
1. 위의 document에서 qty 필드의 값이 20인 모든 문서를 선택합니다.
db.inventory.find( { qty: { $eq: 20 } } )
db.inventory.find( { qty: 20 } )
위의 두 구문은 동일한 결과를 가져옵니다.
{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] }
{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }
2. Embeded Document(객체를 MongoDB에서는 Document로 부르는 듯)의 필드 값을 필터할 수 있습니다.
아이템 Document 내부의 name 필드 값이 ab인 모든 document를 가져옵니다.
db.inventory.find( { "item.name": { $eq: "ab" } } )
db.inventory.find( { "item.name": "ab" } )
위의 두 구문은 동일한 결과를 가져옵니다.
{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] }
3. 배열의 특정 요소(한 개)를 가지는 모든 documents를 가져옵니다.
tag 필드의 배열 중 "B"를 요소로 가지는 모든 documents를 출력합니다.
db.inventory.find( { tags: { $eq: "B" } } )
db.inventory.find( { tags: "B" } )
1번과 동일한 query 방식입니다.
위의 두 구문은 동일한 결과를 가져옵니다.
{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] }
{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] }
{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] }
{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] }
4. 배열의 특정 요소(여러 개)를 가지는 모든 documents를 가져옵니다.
tag 필드의 배열 중 "A", "B"를 요소로 가지는 모든 documents를 출력합니다.
db.inventory.find( { tags: { $eq: [ "A", "B" ] } } )
db.inventory.find( { tags: [ "A", "B" ] } )
위의 두 구문은 동일한 결과를 가져옵니다.
{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] }
{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }
5. query에는 Regex(정규표현식)도 사용할 수 있습니다.
{ _id: 001, company: "MongoDB" }
{ _id: 002, company: "MongoDB2" }
위 documents 중에서 company 필드에 "Mongo"를 포함하는 documents를 가져옵니다.
db.collection.find( { company: { $eq: /MongoDB/ } }, {_id: 0 } )
위의 구문은 아래 결과를 가져옵니다.
(.find 메소드의 두번째 인수는 option으로 { _id: 0 }는 _id 필드를 제외한다는 표현입니다)
{ "company" : "MongoDB" }
{ "company" : "MongoDB2" }
6. $ne는 정반대의 결과를 가져옵니다.
'MongoDB > Comparison Query Operators' 카테고리의 다른 글
[MongoDB] $in, $nin (1) | 2022.06.30 |
---|---|
[MongoDB] $gt, $gte, $lt, $lte (0) | 2022.06.30 |