💡 MongoDB 공식 문서를 참고해서 작성하였다.
참고 : https://docs.mongodb.com/manual/tutorial/query-array-of-documents/
Query an Array of Embedded Documents — MongoDB Manual
Docs Home → MongoDB Manual➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples.The following example selects all documents where an element in the instock array matches the specified document:Eq
docs.mongodb.com
포함된(Embedded) document 배열 쿼리
주어진 예시에 따라 쿼리문을 작성 예시를 보일 것이다.
db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
- 배열에 중첩된(Nested) document 쿼리
ex) instock 배열의 요소가 지정된 document와 일치하는 모든 document 들을 선택한다. →
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
전체 포함/중첩 document에 대한 동등 일치는 field 순서를 포함하여 지정된 document와 정확히 일치해야 한다.
- ex) 다음 쿼리는 inventory collection document와 일치하지 않는다.
db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
- document array의 field에 쿼리 조건 지정
만약 document의 index의 위치를 모르는 경우, 배열 필드의 이름을 점(.)으로 연결하고 중첩된 문서의 필드 이름을 연결합니다.
- ex) instock 배열에 field qyt가 20보다 작거나 같은 조건으로 적어도 한개 포함된 document를 쿼리 한다.
db.inventory.find( { 'instock.qty': { **$lte**: 20 } } )
- document 배열에 대한 여러 조건 지정
document 배열에 중첩된 둘 이상의 필드에 조건을 지정할 때 단일 document가 이러한 조건을 충족하거나 배열의 document 조합(단일 document 포함)이 조건을 충족하도록 쿼리를 지정할 수 있다.
-> 단일 중첩 document가 중첩 field에서 여러 쿼리 조건을 충족한다.
$eleMatch 연산자를 사용해서 여러 기준에 맞는 적어도 하나 이상의 중첩된 document를 통해 배열을 찾을 수 있다.
- ex) warehouse: “A”, qty: “5” 가 포함된 배열
db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )
- ex) instock 배열에 적어도 하나의 document(field qty가 10보다 크거나, 20보다 작거나 같거나)
db.inventory.find( { "instock": { **$elemMatch**: { qty: { $gt: 10, $lte: 20 } } } } )
- 요소의 조합이 기준을 충족할 때
배열 field의 복합 쿼리 조건이 $eleMatch 연산자를 사용하지 않는 경우 쿼리는 해당 배열에 조건을 충족하는 요소 조합이 포함된 document를 선택한다.
- ex) instock 배열에 중첩된 모든 document에 qty보다 10보다 큰 field가 있고 배열에 있는 모든 document에 qty가 20보다 작거나 같은 필드가 일치하는 document를 찾는다.
db.inventory.find( { "instock.qty": { $gt: 10, $lte: 20 } } )
- ex) instock 배열에 5와 동일한 필드 qty를 포함하는 하나 이상의 중첩된 document와 A와 동일한 field warehouse를 포함하는 하나 이상의 중첩된 document가 있는 document를 쿼리 한다.
db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )
'Database > MongoDB' 카테고리의 다른 글
MongoDB - Query에서 반환할 projectjon field (0) | 2021.12.19 |
---|---|
MongoDB - 배열 쿼리 - (1) (0) | 2021.12.19 |
MongoDB - Document Query(조회) - (2) (0) | 2021.12.18 |
MongoDB - Document Query(조회) - (1) (0) | 2021.12.18 |
MongoDB - Database/Collection/Document생성,제거 (0) | 2021.12.18 |