1

I have two databases.

  1. One database with user information.
  2. One database with sales information.

I am trying to aggregate on a collection. I need to do a $lookup with the localField being an user ID in the user database.

How can I do this?

In mongoose I can use populate and specify the model I want to use, like this:

.populate({
  path: 'user',
  select: 'name',
  model: UserModelFromDifferentDB
})

But in the $lookup I can't see such an option?

Example where the issue starts:

        const data = await Sale.aggregate([
        {
            $match: {
                creator: Types.ObjectId("5d5154a37dcf4a00171c0018")
            }
        },
        {
            $lookup:
              {
                from: 'users', // no users collection in this DB, it is in the other db
                localField: 'user',
                foreignField: '_id',
                as: 'user'
              }
        },
      ])
vemund
  • 1,667
  • 4
  • 29
  • 43

1 Answers1

3

As I know it is not possible with aggregate to do $lookup across two databases. But if you can do some logical code then "getSiblingDB()" will help you.

 first_DB_data = db.getSiblingDB('students').bca.find() //'students' is DB,'bca' is collection
 second_DB_data = db.getSiblingDB('marks').finals.find() //'marks' is DB,'finals' is collection

After getting all records from both DB you can perform code for getting your desired output. Now you have all records from both DB you can filter out data on basis of any condition.. Hope it will help you