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

Alexander Suraphel picture Alexander Suraphel · Aug 30, 2016 · Viewed 11.7k times · Source

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?

Answer

Clement Amarnath picture Clement Amarnath · Aug 30, 2016

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