Rahul
Rahul

Reputation: 47106

Mongoid concatenation search

until today I was making simple name search on my user collection with this query

User.where({ '$or'=> [ { firstName: regExp }, { lastName: regExp } ] })

which works fine, but if I want to do my search queries on the full string firstname lastname , should I create an other "fullname" field and or is there a better alternative ?

Upvotes: 1

Views: 508

Answers (1)

marquez
marquez

Reputation: 737

You can use the aggregation framework to perform a projection with the use of the $concat operator and then match the projected field with your regexp.

Anyway a benchmark test against your query would be really useful to know how fast it performs.

User.collection.aggregate(
    {
        :$project => {
            :fullname => {:$concat => ["$firstName", " ", "$lastName"]}
        }
    },
    {
        :$match => {
            :fullname => regExp
        }
    }
)

Upvotes: 2

Related Questions