lolix lolix - 7 months ago 22
Ruby Question

mongodb query with array

I have this collection:

{"_id"=>BSON::ObjectId('5728cd81c08460ead'), "age"=>4, "name"=>"Diogo"}
{"_id"=>BSON::ObjectId('5728cd81c08460ead'), "age"=>22, "name"=>"Tiago"}
{"_id"=>BSON::ObjectId('5728cd81c08460ead'), "age"=>15, "name"=>"Marie"}
{"_id"=>BSON::ObjectId('5728cd81c08460ead'), "age"=>2, "name"=>"JJ"}
{"_id"=>BSON::ObjectId('5728cd81c08460ead'), "age"=>44, "name"=>"John"}


and this array of names:

names_array = ["John", "Marie", "Tiago"]


How can I use names_array to search for names in mongodb collection?

I want this output:

{"_id"=>BSON::ObjectId('5728cd81c08460ead'), "age"=>4, "name"=>"Diogo"}
{"_id"=>BSON::ObjectId('5728cd81c08460ead'), "age"=>22, "name"=>"Tiago"}
{"_id"=>BSON::ObjectId('5728cd81c08460ead'), "age"=>15, "name"=>"Marie"}


this query not work :

coll.find( { name: names_array } )

Answer
coll.find('name' => { '$in' => names_array } } )
Comments