24

I'm trying to do something like this:

use user; 

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

user and organization are in two different databases.

If this is not possible, what are the alternatives?

Alexander Suraphel
  • 9,083
  • 9
  • 48
  • 86

2 Answers2

19

Is it possible to do a $lookup aggregation between two databases in Mongodb?

It is not possible to query using lookup in two different db's. $lookup in mongodb supports Performs a left outer join to an unsharded collection in the same database.

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

We can use getSibling("dbname") to query another db from one db

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

Reference - MongoDB cross database query

Community
  • 1
  • 1
Clement Amarnath
  • 5,073
  • 1
  • 19
  • 32
7

Yes just read the following mongodb doc:

In Atlas Data Lake, $lookup can be used to perform a join of collections from different databases.

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

Steven
  • 1,662
  • 3
  • 20
  • 32
Gnopor
  • 236
  • 5
  • 9