Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb - check if field is one of many values

Tags:

mongodb

Is there an efficient way to query a document by if a field-value is equal to at least one value in an array?

for example when I have the following documents:

{email:"[email protected]"},
{email:"[email protected]"},
.
.
.
{email:"[email protected]"}

and have indexed the email field, I want to get all document's ids, whose email field's value is equal to either "[email protected]","[email protected]" or 100 other totally unrelated email addresses. Is it possible?

I thought it would be as easy as

db.users.find({email:["[email protected]","[email protected]", ... 99 entries ..., "mail [email protected]"]})

but I was wrong.

Whats the most efficient way to do this?

like image 499
Van Coding Avatar asked Apr 17 '14 15:04

Van Coding


1 Answers

You can use the $in operator to match any of the values in an array:

db.users.find(
    {email : {$in : ["[email protected]", "[email protected]", "mail [email protected]"]}}
)
like image 174
Anand Jayabalan Avatar answered Oct 16 '22 10:10

Anand Jayabalan