Reputation: 507
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.
Upvotes: 3
Views: 220
Reputation: 119
You would need to use the aggregation framework as follows:
db.test.aggregate(
{ $match: { "id": 1 }},
{ $unwind: '$items' },
{ $match: { "items.value": 5 }},
{ $project: { "_id": 0 }}
)
Return value:
{ "id" : 1, "items" : { "value" : 5 } }
Upvotes: 1
Reputation: 2204
You need to specify the fields you want to return from the query.
documents.find({
items: {
$elemMatch : {
value: { $eq: 5 }
}
},
}, {requiredFields: 1});
See example in this question.
Official docs: here - Search for "select"
If you need to filter out the results too, you an use the $filter
Upvotes: 0