Database/mongoDB
[MongoDB] $unwind 예제
데브포유
2017. 4. 4. 00:00
반응형
첫번째 예제) 하나의 도큐먼트를 sizes의 배열 요소로 분리함
{ "_id" : 1, "item" : "ABC1", sizes: [ "S", "M", "L"] }
db.inventory.aggregate( [ { $unwind : "$sizes" } ] )
{ "_id" : 1, "item" : "ABC1", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "L" }
_id:1인 다큐먼트를 sizes 배열의 요소 갯수만큼 document로 분리함.
RDBMS의 데카르트곱(카데시안곱)과 같은 동작을 함.
두번째 예제) sizes 배열의 요소의 순번 표시하기
{ "_id" : 1, "item" : "ABC", "sizes": [ "S", "M", "L"] } { "_id" : 2, "item" : "EFG", "sizes" : [ ] } { "_id" : 3, "item" : "IJK", "sizes": "M" } { "_id" : 4, "item" : "LMN" } { "_id" : 5, "item" : "XYZ", "sizes" : null }
db.inventory.aggregate( [ { $unwind: { path: "$sizes", includeArrayIndex: "arrayIndex" } } ] )
{ "_id" : 1, "item" : "ABC", "sizes" : "S", "arrayIndex" : NumberLong(0) } { "_id" : 1, "item" : "ABC", "sizes" : "M", "arrayIndex" : NumberLong(1) } { "_id" : 1, "item" : "ABC", "sizes" : "L", "arrayIndex" : NumberLong(2) } { "_id" : 3, "item" : "IJK", "sizes" : "M", "arrayIndex" : null }
세번째 예제) sizes의 원소가 없거나 null이어도 출력하라
db.inventory.aggregate( [
{ $unwind: { path: "$sizes", preserveNullAndEmptyArrays: true } }
] )
{ "_id" : 1, "item" : "ABC", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC", "sizes" : "L" }
{ "_id" : 2, "item" : "EFG" }
{ "_id" : 3, "item" : "IJK", "sizes" : "M" }
{ "_id" : 4, "item" : "LMN" }
{ "_id" : 5, "item" : "XYZ", "sizes" : null }
반응형