skip to Main Content

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.

3

Answers


  1. 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"
       }
      }
      ]);
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. If your collcetions are closely related, they should preferably be in the same database, as mentioned by other answers.

    However, if you are running your MongoDB through MongoDB Atlas, you would be able to achieve what you describe, using Federated Databases to Query across multiple Atlas clusters. Then you can run aggregation pipelines that joins the two.

    I am currently using this to query across two atlas clusters (a data warehouse with cold data, and a database with live data).

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search