Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB find by matching two concatened fields?

Tags:

mongodb

I have a MongoDB collection that has firstName & lastName fields, I need to retrieve items that matches specific fullNames:

Is there an easy way to write a query that would check that:

firstName + " " + lastName IN ARRAY ()... ?

--- EDIT ---

The reason to concatenate is that I don't want bill jobs in the result (considering it exists) if I have [bill, steve] for firstNames & [gates, jobs] for lastname.

Thanks!

like image 985
Olivier Avatar asked Feb 20 '12 13:02

Olivier


2 Answers

Surely you just want:

db.myCollection.find({firstName:"bill",lastName:"gates"})

or is there a specific reason to actually concatenate?

like image 109
Rich Avatar answered Sep 24 '22 06:09

Rich


It sounds like you have the concatenated fields as your input. If that's the case, you'd be much better off splitting your input data in whatever language you're using and passing the separate fields to MongoDB.

var names = "bill gates".split();
db.myCollection.find({firstName:names[0],lastName:names[1]});

This will also let MongoDB use an index if one is defined.

like image 28
michaeltwofish Avatar answered Sep 26 '22 06:09

michaeltwofish