0

I am trying to filter a MongoDB collection with a structure similar to:

{
   Name: "My Item",
   Attributes: [{
        AttributeId: 1,
        Values: [{
               Name: "Book",
               P: 10
        },
        {
               Name: "Series",
               P: 100
        }] 
      },
      {   
        AttributeId: 2,
        Values: [{
              Name: "Pen",
              P: 10
        },
        {
              Name: "Dozen",
              P: 100
        }]
  }]
}

What I want is to get all documents with AttributeId: 1 and has a value inside it named "Book".

I have tried this filter but it didn't return any results:

{"ProductAttributeMappings.ProductAttributeId": 32,"ProductAttributeMappings.$.ProductAttributeValues.Name":"Book"}

2 Answers 2

1

If I understand you correctly, you are trying to do this:

This query checks inside Attributes array to match both conditions (Attribute==32 and Values.Name==Book)

db.ProductAttributeMappings.find({
  Attributes: {
    $elemMatch: {
      AttributeId: 32,
      Values: {
        $elemMatch: {
          Name: "Book"
        }
      }
    }
  }
})

MongoPlayground

But, this query checks inside entire top-level document if any array meets query condition:

db.ProductAttributeMappings.find({
  "Attributes.AttributeId": 32,
  "Attributes.Values.Name": "Book"
})

MongoPlayground

Sign up to request clarification or add additional context in comments.

Comments

1

You need elemMatch operator:

{Attributes: {$elemMatch: {AttributeId: 1, "Values.Name": "Book"}}}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.