0

If this is my data:

{
  owner: 'John',
  pets:[
    {
      name: 'Oscar',
      age: 7,
      type: 'dog'
    },{
      name: 'Oscar II',
      age: 3,
      type: 'dog'
    }
  ]
},{
  owner: 'Sally',
  pets:[
    {
      name: 'Spot',
      age: 7,
      type: 'cat'
    },{
      name: 'Mister Dog',
      age: 3,
      type: 'dog'
    }
  ]
}

How can I build a query to get every owner that has a dog that is 7.

I tried:

Owners.findOne({
  'pets.age': 7,
  'pets.type': 'dog'
});

But this returns every owner who has a pet with an age of 7 OR with a type of dog. In the case of the data above it return both Sally & John. How can I just get John?

1 Answer 1

1

Use $elemMatch to specify all constraints to the same element:

Owners.findOne({
  'pets': {
      '$elemMatch' : {
          'age': 7,
          'type': 'dog'
       }
   }
});
Sign up to request clarification or add additional context in comments.

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.