14

I am trying to develope a searcher in my web app, i am using mongodb... so... i have a document, with this information.

{
    "_id": "458734895734",
    "name": "user",
    "ref": "1",
    "data": "fdnsfkjndjfn"
},
{
    "_id": "3332423333",
    "name": "user1",
    "ref": "2",
    "data": "dvsdvdvds"
}

i am using $regex for match the search with my app. so i have this in my server node.js.

db.users.find({ 
    name: {'$regex': query, '$options': 'i'}
}).then((users) => {
    res.json(users);
})

        // var query, is just the pattern that i send from my web

As you can see, my server is only searching in the field 'name', how can i add other field like 'ref' and search in both fields at the same time?? i've checking the documentation in mongodb but i could not find it...

2 Answers 2

31

This is because the way you wrote the query which means it should match the given regex query with all passed parameter like and(&&) operation. What you could do is make and or(||) operation with all the required fields.

Here the sample code you can try.

db.users.find({
    "$or": [
        { name: { '$regex': query, '$options': 'i' } },
        { ref: { '$regex': query, '$options': 'i' } }
    ]
}).then((users) => {
    res.json(users);
});
Sign up to request clarification or add additional context in comments.

2 Comments

perfect ! exactly, i was missing OR operator... thank you!
@pavan-vora I'm with a similar problem, but in my case name and ref could be anything. Is it possible to handle that?
-2

The OR operator, regex or options doesn't need to be in quotes. Below works for me:

db.users.find({
$or: [
    { name: { $regex: query, $options: 'i' } },
    { ref: { $regex: query, $options: 'i' } }
]
}).then((users) => {
    res.json(users); 
});

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.