sourcetip

Mongodb에서 두 데이터베이스 간에 $lookup 집계가 가능합니까?

fileupload 2023. 7. 17. 21:22
반응형

Mongodb에서 두 데이터베이스 간에 $lookup 집계가 가능합니까?

저는 다음과 같은 일을 하려고 합니다.

use user; 

db.user.aggregate([
    {
      $lookup:
        {
          from: "organization.organization",
          localField: "organizationId",
          foreignField: "uuid",
          as: "user_org"
        }
   }
])

user그리고.organization두 개의 다른 데이터베이스에 있습니다.

만약 이것이 불가능하다면, 대안은 무엇입니까?

Mongodb에서 두 데이터베이스 간에 $lookup 집계가 가능합니까?

두 개의 다른 DB에서 조회를 사용하여 쿼리할 수 없습니다.mongodb에서 $lookup 지원 동일한 데이터베이스의 공유되지 않은 컬렉션에 대한 왼쪽 외부 조인을 수행합니다.

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

우리는 사용할 수 있습니다.getSibling("dbname")한 DB에서 다른 DB를 쿼리합니다.

db.getSiblingDB('test').foo.find()

참조 - MongoDB 데이터베이스 간 쿼리

예, 다음 mongodb 문서를 읽으십시오.

아틀라스 데이터 레이크에서$lookup다른 데이터베이스의 컬렉션 조인을 수행하는 데 사용할 수 있습니다.

https://docs.mongodb.com/datalake/reference/pipeline/lookup-stage

다음은 Atlas Data Lake를 사용하지 않는 사용자를 위한 해결 방법입니다.

우리가 가지고 있다고 가정해 봅시다.collection1db1그리고.collection2db2.

부터db1첫 번째 합병collection2

db.getSiblingDB("db2").collection2.aggregate([
    {
        $match: { "key1": "optional some condition to limit the number of results" }
    },
    {
        $project: { k2: "$optional projection to limit object attributes" }
    },
    {
        $merge: { into: { db: "db1", coll: "tmpCollection2" } }

    }
])

그런 다음 컬렉션1을 사용하여 조회합니다.

db.collection1.aggregate([
    {
        $lookup: {
            from: "tmpCollection2",
            localField: "localField",
            foreignField: "k2",
            as: "tmpCollection2_docs"
        }
    },
    {
        //Simulate the inner join if needed
        $match: {
            "tmpCollection2_docs": {
                $ne: []
            }
        }
    },
    {
       // Transform the array if needed
        $addFields: {
            "tmpCollection2_docs": {
                $arrayElemAt: ["$tmpCollection2_docs", 0]
            }
        }
    }
])

언급URL : https://stackoverflow.com/questions/39222798/is-it-possible-to-do-a-lookup-aggregation-between-two-databases-in-mongodb

반응형