How to make a "JOIN" in two Colections in Mongodb?

Asked

Viewed 1,682 times

6

I know Mongodb doesn’t have Ner Join, but I really need to filter the data from a Collection by reference to its _id in another Collection.

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

No question of restructuring the base.

Collections:

usuarios: { _id: ObjectId("..."), nome: "usuario", ... }

projects:

{ _id: ObjectId("..."), nome: "projeto1", ...}

users:

{ _id: ObjectId("..."), idProjeto, idUsuario }

In short, I want to pass the _id user and he bring me all his projects without changing the structure above. It is possible?

  • 1

    You want to do it inside the Mongo Shell?

  • Whatever. I wonder if there’s a way out.

  • 1

    It exists, but it involves a programming language. Mongodb, as the answer given, does not have native support for joins. You who have to make your application read the dependent data.

  • You have the code of some solution with php for me to understand?

  • 1

    http://www.sitepoint.com/modeling-data-relationships-in-mongodb/

2 answers

7


Mongodb can’t stand it joins.

Unfortunately its structure does not match the functioning of Mongodb.

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

The data from Collection usuariosProjetos should be part of Collection usuarios.

  • 1

    Well, there is no concept of "table" in Mongodb because it is a database without schema. The schema is defined in the application.

  • Yes, I changed the terms, I meant Collection

  • Now it’s okay. + 1.

2

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.