MongoDB (Mongoose & Mongo Client PHP) search in concat field
You can use the $where operator in the find()
query:
db.persons.find({$where:function(){ var search = /John A/; var matchA = (this.name+" "+this.middlename+" "+this.lastname).match(search); var matchB = (this.lastname+" "+this.middlename+" "+this.name).match(search); return !!(matchA || matchB);}})
or, you could aggregate the results.
Project
two extra fields, which contain the concatenated value.(use $concat operator.)Match
using a regular expression pattern.(SQL to Mongo Mapping chart.)
MongoDb aggregation pipeline:
var search = /John A/;db.persons.aggregate([{$project:{"concat_name_a":{$concat:["$name"," ","$middlename"," ","$lastname"]}, "concat_name_b":{$concat:["$lastname"," ","$middlename"," ","$name"]}, "name":1,"middlename":1,"lastname":1}},{$match:{$or:[{"concat_name_a":search},{"concat_name_b":search}]}},{$project:{"name":1,"middlename":1,"lastname":1}}])
Going for either of the approaches would be fine here, since both the approaches cannot make use of any indexes on the collection.