Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get precise subdocuments in document array mongoose

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.

like image 587
Thomas Blanquet Avatar asked Aug 06 '26 05:08

Thomas Blanquet


1 Answers

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 } }
like image 199
Karel Avatar answered Aug 08 '26 19:08

Karel