Strife86
Strife86

Reputation: 1155

MongoDB (Mongoose & Mongo Client PHP) search in concat field

Given a structure like { name: String, middlename: String, lastname: String } is there a way in mongo both mongoose for node and in php to search a term in the concatenation of the fields, for example in mysql i can do something like

select * from persons 
    where concat_ws(' ',name, middlename, lastname) like '%John A%' OR
    concat_ws(' ',lastname, middlename, name) like '%John A%'
    group by id

this way i dont need to explicitly make inputs for every field just one but i dont see how to accomplish something like that in mongo

Upvotes: 2

Views: 1050

Answers (1)

BatScream
BatScream

Reputation: 19700

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.

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.

Upvotes: 3

Related Questions