javascript - Search 2 text fields as 1 field -
i'm search users name , i've properties: firstname
, lastname
. if had property fullname
trivial don't have it.
i want search "peter robert" , need combine theses 2 fields 1 before searching.
how do it?
sounds want "text search". text indexes can span on multiple fields terms entered searched indexed fields:
db.collection.ensureindex({ "firstname": "text", "lastname": "text" }) db.collection.find({ "$text": { "$search": "peter robert" } })
that 1 way handle this. return other matches exact matches have highest score can rank them.
alternately, if know getting string "peter robert" in order can "split" , tokenize input:
var input = "peter robert"; var parts = input.split(/ /); // splits on space db.collection.find({ "firstname": parts[0], "lastname" parts[1] ])
which pretty basic. or apply $regex
, $or
operators in mix:
var input = "peter robert"; var regexstr = input.split(/ /).join("|"); // make "peter|robert" db.collection.find({ "$or": [ { "firstname": { "$regex": regexstr } }, { "lastname": { "$regex": regexstr }} ] })
honestly, can $where
operator , javascript. not best though since condition evaluate every document:
db.collection.find(function(){ return ( this.firstname + " " + this.lastname ) == "peter robert"; })
probably plays bit better aggregation framework though:
db.collection.aggregate([ // borrow above "might" match documents { "$match": { "$or": [ { "firstname": { "$regex": regexstr } }, { "lastname": { "$regex": regexstr }} ] }}, // project "fullname" { "$project": { "firstname": 1, "lastname": 1, "fullname": { "$concat": [ "$firstname", " ", "$lastname" ] } }}, // match on fullname value { "$match": { "fullname": input } } ])
many ways this. not restricted frameworks ( such "emulate" mongo functions on client ) since there both multiple ways process , server side operations "text search" , aggregation , "javascript queries" can done in server logic code.
Comments
Post a Comment