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...
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With