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: "[email protected]"
},
{
    name: "bug",
    phone: "84567521",
    email: "[email protected]"
},
{
    name: "bug2",
    phone: "84567521",
    email: "[email protected]"
 }

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

4
  • Do you have some example data to clarify your question with, together with the expected output of the required query? Commented Oct 25, 2015 at 14:56
  • added example data and expected result Commented Oct 25, 2015 at 15:12
  • Possible duplicate of How to query mongodb with "like"? Commented Oct 25, 2015 at 18:10
  • 1
    Its different because I'm asking what is the best way to query "like" on number of fields. Commented Oct 26, 2015 at 7:58

1 Answer 1

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" : "[email protected]"
}

/* 1 */
{
    "_id" : ObjectId("562cf265d3ea50dcd6085c54"),
    "name" : "bug2",
    "phone" : "84567521",
    "email" : "[email protected]"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.