Reputation: 3166
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,
Upvotes: 2
Views: 107
Reputation: 84
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);
Upvotes: 0
Reputation: 151220
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.
Upvotes: 1
Reputation: 6539
Your query should be:-
db.collection.find( { category: { $in: [ 'cat', 'has_claws' ] } } )
Upvotes: 0