This stretch of the answer is valid even before version 3.2. For version 3.2 onwards, see the rest of the answer.
Using only findOne()
or other find
methods, is not possible because MongoDB does not support joins, according to official documentation .
What you can do is to use a framework in your programming language of choice to resolve the references for you.
This excerpt from the answer to version 3.2 onwards. Thanks to @PauloLuvisoto for Response Completion .
As of version 3.2 of MongoDB there is the $lookup
operator, able to make a join between two collections.
In the example below we have a collection called 'products', with the fields _id
, descricao
and valor
. We also have another collection called 'Orders' with the fields _id
, nome_cliente
, cidade
and id_produto
. This field id_produto
of the 'requests' collection will be linked to the _id
field of the 'products' collection.
We will perform the rendering as follows:
db.pedidos.aggregate([
{
$lookup:
{
from: "produtos",
localField: "id_produto",
foreignField: "_id",
as: "desc_produto"
}
}])
We'll get a result like this:
{ "_id" : ObjectId("5685c8c74ad088fc05dcebe7"), "usuario" : "Carlos", "id_produto" : 1, "cidade" :
"Franca", "desc_produto" : [ { "_id" : 1, "titulo" : "Camisa", "valor" : 1500.3 } ] }
{ "_id" : ObjectId("5685c8d94ad088fc05dcebe8"), "usuario" : "Paulo H", "id_produto" : 2, "cidade" :
"Batatais", "desc_produto" : [ { "_id" : 2, "titulo" : "Saia", "valor" : 236.47 } ] }
You can use $lookup
to join join between more than two tables. Example:
db.pedidos.aggregate([
{
$lookup:
{
from: "produtos",
localField: "id_produto",
foreignField: "_id",
as: "desc_produto"
}
},
{
$lookup:
{
from: "clientes",
localField: "id_cliente",
foreignField: "_id",
as: "desc_cliente"
}
}])
Mooring can be done through any field, not just through the _id
fields as shown in the examples.