Gary Kipnis
Gary Kipnis

Reputation: 732

How to search for two fields in two arrays in mongodb nodejs

Two of the fields in my mongodb record are: first and last

I am presented with two arrays: first_array = [bob, gary, john] last_array = [smith, evans, johnson]

There is a one to one correspondence between first and last names in the two arrays. I want to find the records for BobSmith, GaryEvans and JohnJohnson.

find({first:{$in:first_array}}) will find all records matching first names but not last names find({last:{$in:last_array}}) will find all records matching last names but not first names find({first:{$in:first_array}, last:{$in:last_array}}) will find all of my records, but it will also find records such as BobEvans and GarySmith (if they exist)

Thanks in advance for any suggestions, Gary

Upvotes: 0

Views: 157

Answers (1)

Asya Kamsky
Asya Kamsky

Reputation: 42352

where = {};
where["$or"] = [ ];
for (i=0; i<first_array.length; i++) {
    where["$or"].push( {"first": first_array[i], "last":last_array[i]} );
}

db.collection(where)

Upvotes: 2

Related Questions