DB/MongoDB

[mongo] 몽고 DB Join 방법 . 몽고 버전에 따른 lookup, 다른 DB 컬렉션 join

벨포트조던 2022. 8. 31.
반응형

목표

같은 서버의 다른 DB의 컬랙션 둘을 Join 하여 조회하고 싶었음 

현재 사용 몽고 버전은 4.0 

 

TestDB1 -> collenction1

TestDB2 -> collenction2

 

예를들면 위 두 컬렉션을 join 할 필요가 생겼음 

 

과거에 몽고 join이 안된다는 말을 많이 들었었고, 이후에 할 필요성이 없었어서.. 관심 밖이었다가 이번에 찾아보게됨

주변 개발자들이 몽고 join 경험이 없어서 많이 찾아봄

 

RDB 처럼 join 을 하는건 아니고... lookup을 이용하여 ... join 느낌을 내는것같다.

내부 로직은 잘 모르겠다. 

 

샘플코드

// Requires official MongoShell 3.6+
db = db.getSiblingDB("p_test");
db.getCollection("test_collection").aggregate(
    [
        {
            "$match" : {
                "idx" : 7477074.0
            }
        }, 
        {
            "$lookup" : {
                "from" : "pushuser_201802260910",
                "localField" : "idx",
                "foreignField" : "idx",
                "as" : "test"
            }
        }
    ], 
    {
        "allowDiskUse" : false
    }
);

일단..위 샘플코드처럼 사용하면 결과가 나온다... 다만 .. 

 

버전에 따라 불가능한게 있다.

 

1. lookup은 3.2 버전부터 가능하다.

2. 현재 4.0 버전에는 타 컬렉션

3. Starting in MongoDB 5.1, $lookup works across sharded collections.

문서보니까.. 5.1부터 타 DB에 있는 컬렉션과 lookup 가능 

4. 위 이유로 안되서.. view를 생성하는 것도 고려해봤는데, 그것도 4.2버전부터 가능한 것으로보임 

 

이와 같은 이유로 ... 버전을 올리는 방법이 아니면 ... lookup 을 사용할 수 없어서 .. 

코드로 해결방향을 잡았다.

 

 

 

버전 차이로 가능한 방법이 다르니 ... 참고해야겟다.

https://www.mongodb.com/docs/v6.0/reference/operator/aggregation/lookup/

 

$lookup (aggregation) — MongoDB Manual

Docs Home → MongoDB Manual $lookupPerforms a left outer join to a collection in the same database to filter in documents from the "joined" collection for processing. The $lookup stage adds a new array field to each input document. The new array field con

www.mongodb.com

 

lookup 참고

https://joyful-development.tistory.com/21

https://www.delftstack.com/ko/howto/mongodb/mongodb-join-two-collections/

 

 

반응형

댓글