Search code examples
mongodbmongodb-querymongodb-aggregation

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


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?


Solution

  • 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