I'm developing a graphql API using mongoose to interact with my mongo database and I'm struggling with something. I have documents with subdocuments arrays and I need to get all the documents containing a subdocument that have a specific field value. The problem is I want to get only this subdocument in the document. It's easier to explain with an example :
My documents are like that :
documents: [
{
id: 1,
items: [
{
value: 5,
},
{
value: 10,
},
]
},
{
id: 2,
items: [
{
value: 7,
},
{
value: 10,
},
]
}]
I want to get all the documents that have an item with value == 5
, but containing only this value like :
results : [
{
id: 1,
items: [
{
value: 5,
}
]
}]
What I do for now is :
documents.find({
items: {
$elemMatch : {
value: { $eq: 5 }
}
},
});
The thing is doing this I get the correct document, but it contains all the items, not only the ones that match the condition. I looked for a solution but I didn't find anything to do so.
Thanks for your help, I hope it is clear enough.