Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to find with $regex multiple fields at the same time in Mongodb

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...

like image 725
Sergio Cano Avatar asked Aug 20 '18 14:08

Sergio Cano


1 Answers

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);
});
like image 87
Pavan Vora Avatar answered Nov 14 '22 23:11

Pavan Vora