2

I need to query MongoDB on the number of the fields: name, phone, email. And the query should support "like" syntax: '%s%' What is the better way to perform it:

  1. Query on number of fields with $or
  2. Create array field with values of the above fields and multikey index on this field

An example collection contains the following documents

{
    name: "Evgeny3345",
    phone: "4678946",
    email: "trial@stack.com"
},
{
    name: "bug",
    phone: "84567521",
    email: "bug@stack.com"
},
{
    name: "bug2",
    phone: "84567521",
    email: "deny@stack.com"
 }

When I find all documents with name or phone or email containing "eny", this should return documents 1 and 3.

chridam
  • 100,957
  • 23
  • 236
  • 235
user1982978
  • 61
  • 1
  • 6

1 Answers1

1

Best create a RegExp object with the search pattern and use that with the $or expression that references all the three fields. Something like

var rgx = new RegExp('ny', 'i'),
    query = {
        "$or": [
            { "name": rgx },
            { "phone": rgx },
            { "email": rgx }
        ]
    };
db.collection.find(query)

Sample output:

/* 0 */
{
    "_id" : ObjectId("562cf265d3ea50dcd6085c52"),
    "name" : "Evgeny3345",
    "phone" : "4678946",
    "email" : "trial@stack.com"
}

/* 1 */
{
    "_id" : ObjectId("562cf265d3ea50dcd6085c54"),
    "name" : "bug2",
    "phone" : "84567521",
    "email" : "deny@stack.com"
}
chridam
  • 100,957
  • 23
  • 236
  • 235