2

I'd like to find documents from a collection that has for example a category 'cat'

i.e.

[{id: 0, name: 'cheetah', category: ['cat', 'has_claws']},
 {id: 1, name: 'lion', category: ['cat', 'has_claws', 'alpha']},
 {id: 2, name: 'fox', category: ['dog']},
 {id: 3, name: 'eagle' category: ['bird', 'has_claws']}
]

What does the query should look like? For example, I wanted to query allo animals that is in the category has_claws, I also wanted to make sure, there wouldn't be any duplicates, when I query using an array instead..

I.e. I want to query animals that is in cats and in has_claws

I thought using $in will suffice

$query   = array('category' => array('$in' => array('cat', 'has_claws')));
$animals = $animalModel->find($query);

is there a native function to do this,

3 Answers 3

1

Looks like you want $all

$query   = array('category' => array('$all' => array('cat', 'has_claws')));
$animals = $animalModel->find($query);

Which means the field must have "both" values to be a match. The $in operator instead means "either" of the values can match, so "three" of your documents as opposed to "two" that $all would match.

Also you named the field incorrectly in your question. Corrected to "category" here.

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

Comments

0

Your query should be:-

db.collection.find( { category: { $in: [ 'cat', 'has_claws' ] } } )

Comments

0

If you want to query for all the animals having category cat and has_claws with no duplicate you can use distinct function.

$query=array('name',array('category' => array('$in' => array('cats', 'has_claws')); $result = $collection->distinct($query);

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.