I have a collection called user which has the following structure.
{
"_id" : ObjectId("5d4ae50fbdc1cd6351dab49f"),
"nombre" : "usuario1",
"Correo" : "[email protected]",
"playlist" :
[
{
"nombrePlay" : "play1",
"descPlay" : "descPlay",
"canciones" :
[
ObjectId("5d4ae655bdc1cd6351dab4c5")
]
}
]
}
I have a collection of Songs with the following structure
{
"_id" : ObjectId("5d4ae655bdc1cd6351dab4c5"),
"nombreCancion" : "cancion1",
"detalleCancion" : "detalleCancion"
}
what I try is that when I get to usuario1
not only show me the list playlist
but also the description of the song..
but when doing a db.usuarios.find()
returns me the same structure that shown at the beginning to insert the data I base on the following part of the documentation
Assuming you use MongoDB 3.2+ (I hope so), to get the data from one collection over another using the reference you indicated, you must use an Aggregation process , which must consist of two stages:
$match
: During this stage a filter is performed to allow only the documents that match the given filter. In your particular case the filter would be:{"nombre": "usuario1"}
. In this way, the documents returned will be all those whose name field matches the filter.$lookup
: During this stage, a search is made (on the same database) of the elements of another collection that correspond to the value saved as a reference in the collection on which the aggregation is applied. The parameters used in this stage are:from
: Indicates the collection from which the referenced data will be extracted. In your case it iscanciones
.localField
: Indicates the field of the collection (on which the aggregation is applied), which contains the references to another collection. In your case, the local field isplaylist.canciones
.foreignField
: Indicates the field (of the collection indicated infrom
) that matches the reference indicated inlocalField
. In your case, the field is , since you have saved the values of the documents in the collection_id
as a reference ._id
canciones
as
: Specifies the name of the newArray
one that will contain the documents of the collection (specified infrom
) with the requested data. If the field does not exist, it will be added to the result, however, if it does exist, it will be replaced with the requested data. In your case you can overwrite the fieldplaylist.canciones
.So your query can look like this:
The result obtained can be seen as follows:
I hope this clarifies your doubt and helps you solve the problem.
Note
Array
with the processed documents.$lookup
has a restriction on sharded collections (sharded
). You can read more at Sharded Collection Restrictions