3

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.

2 Answers 2

1

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 } }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.