Home > Mobile >  How can I join two collections from different databases in mongoDB?
How can I join two collections from different databases in mongoDB?

Time:11-24

I have two collections Post (belongs to posts database) and User (belongs to account database). My requirements to do join on these two collection. But I am unable to reproduce my requirements.

I am expecting joins on two collections.

CodePudding user response:

I think you have only one Database having Post and User collections and not two separate databases. If yes then you can use MongoDB lookup aggregation to get the joined data using a single query.

db.Post.aggregate( [
        {
 $lookup:
   {
     from: "User",
     localField: "post_user_id",
     foreignField: "user_id",
     as: "post_docs"
   }
  }
  ]);

CodePudding user response:

This is currently not supported. There is a requirement in the backlog of MongoDB (https://jira.mongodb.org/browse/SERVER-34935) though.

As of now the only option you have is to manually query the two different databases and merge the results together as needed. Nevertheless from my point of view it's a little bit odd to have different databases for related collections. Maybe you can also think about redesigning your database design, if possible.

  • Related