Document structure example
{
"_id" : ObjectId("5d4ae50fbdc1cd6351dab49f"),
"nombre" : "usuario1",
"Correo" : "[email protected]",
"playlist" :
[
{
"nombrePlay" : "play1",
"descPlay" : "descPlay",
"canciones" :
[
{
"nombre":"canción1",
"año":"07/09/2019"
},
{
"nombre":"canción2",
"año":"07/09/2019"
}
]
}
]
}
What I want
When searching, I am interested in only showing me the data that I am requesting and not the entire structure of the document.
What I want to return is something similar to the following
{
"nombre":"canción1",
"año":"07/09/2019"
}
Even something valid would be the following
"canciones" :
[
{
"nombre":"canción1",
}
]
how i tried
db.users2.find({
"nombre": "usuario1",
"playlist.nombrePlay": "play1",
"playlist.canciones.nombre": "canción1"
},
{
"playlist.canciones.nombre": "canción1"
})
Result
It shows me only the data that I want, the problem is that it also returns the structure of the document and the other elements of the list . When I only want the element that I am looking for .
{
"_id" : ObjectId("5d4ae50fbdc1cd6351dab49f"),
"playlist" :
[
{
"canciones" :
[
{
"nombre":"canción1",
"año":"07/09/2019"
},
{
"nombre":"canción2",
"año":"07/09/2019"
}
]
}
]
}
To obtain the desired response you must use aggregations, with the following you would obtain the desired result
Result
You could also make the search easier and then in code manipulate the JSON to obtain the values of the "songs" array
Result
To obtain more than one result in the playlist you must use the following
Result:
In this case you can't remove the root of the playlist since it is an array.
If I understand what you want correctly, you're going to have to do it with aggregation.
See if this would work for you:
This will give you a cursor that traversing it will give the following, although it can be changed by modifying the $project stage:
On the other hand, in your document example you have put
"nombre" : "usuario1"
but you have"name": "usuario1"
in the code in which you have tried it (I imagine that it will be an error having passed it here).Lastly, I have put as output
fecha
instead ofaño
, since I think it is better to avoid the ñs (as well as the code tildes).