본문 바로가기
DB/MongoDB

데이터 베이스(No SQL) - MongoDB Lookup 연산자

by nomfang 2021. 1. 26.
728x90
반응형

$lookup 연산자

MongoDB는 NoSQL이기 때문에 조인이라는 기능이 없다

 $lookup 이라는 연산자를 활용하여 조인과 동일하게 컬렉션을 합칠 수 있다

#문법 { $lookup: { from: <조인 할 컬렉션>, localField: <입력할 도큐먼트의 필드>, foreignField: <'from' 컬렉션의 도큐먼트에 있는 필드>, as: <출력할 배열 필드> } }

필드의미

from 동일한 데이터베이스 내 수행할 컬렉션을 지정합니다.
localField 도큐먼트로부터 $lookup에 입력할 필드를 지정합니다.
foreignField from 컬렉션에 있는 도큐먼트에서 필드를 지정합니다.
as 입력 도큐먼트에 추가될 새 배열 필드를 지정합니다.

SQL과 비교하기

#MongoDB { $lookup: { from: <collection to join>,

localField: <field from the input documents>,

foreignField: <field from the documents of the "from" collection>, as: <output array field> } }

 

#SQL SELECT *, <output array field> FROM collection WHERE <output array field> IN (SELECT * FROM <collection to join> WHERE <foreignField>= <collection.localField>);

예시

아래와 같이 orders 컬렉션과 inventory 컬렉션이 있다고 가정

orders 컬렉션 내에 inventory 컬렉션을 넣어 Embedded Document 구조로 컬렉션 생성

 

orders.insert( [ { "_id": 1, "item": "cake", "price": 10, "quality": 3 },

{ "_id": 2, "item": "cookies", "price": 5, "quality" : 2 }, { "_id": 3 } ]);

inventory.insert([ {"_id": 1, "store": "cake", "description": 1, "sweet": 10},

{"_id": 2, "store": "chocolate", "description": 2, "sweet": 15},

{"_id": 3, "store": "candy", "description": 3, "sweet": 13},

{"_id": 4, "store": "cookies", "description": 4, "sweet": 7},

{"_id": 5, "store": "sandwitch", "description": null}, {"_id": 6 } ])

 

두 컬렉션을 합쳐 새로운 컬렉션 하나를 생성

orders.aggregate([ { $lookup: { from: "inventory", localField: "item", foreignField: "store", as: "inventory_docs" } }, { $out : "newcol1" } ])

 

localField와 foreignField는 조인할 키 값이라고 생각하고, as는 새로 생성되는 필드명

이렇게 쿼리를 작성하게 되면 $out 메서드에 영향을 받아 newcol1 이라는 컬렉션이 생성된다

출력된 결과가 아래와 같이 입력 된다

 

#결과값 { "_id" : 1, "item" : "cake", "price" : 10, "quantity" : 3, "inventory_docs" : [ { "_id" : 1, "store" : "cake", "description" : 1, "sweet" : 10 } ] } { "_id" : 2, "item": "cookies", "price": 5, "quality" : 2, "inventory_docs" : [ {"_id": 4, "store": "cookies", "description": 4, "sweet": 7} ] } { "_id" : 3, "inventory_docs" : [ {"_id": 5, "store": "sandwitch", "description": null}, {"_id": 6 } ] }

반응형

댓글