How to do a “JOIN” in two collections in MongoDB?

Posted on

Question :

I know that mongo has no inner join,

But I need to filter the data of a collection by reference to its _id in another collection.

I need to display only the projects of a given user.

Out of the question restructure the base.


users: {_id: ObjectId (“…”), name: “user”, …}

Projects: { _id: ObjectId (“…”) , name: “project1”, …}

In short, I want to pass the user id and it bring me all his projects without changing the structure above. Is it possible?


Answer :

MongoDB does not support joins .

Unfortunately, its structure does not fit MongoDB’s operation.

Mongodb is a non-relational database, you should centralize the data of each query in the same document.

The data from the collection usuariosProjetos should be part of the collection usuarios .


Adding that from its version 3.4, mongodb brings the $ lookup operator, which allows joining records of two collections, from some common value between the two. But that’s just it. Complex joins as in relational banking, forget.


Leave a Reply

Your email address will not be published. Required fields are marked *