I am trying to find 3 different field values while searching with .find() method and it gives either complete data or only one.
This is the code I have given:
const search = req.query.search || "";
const Rest = await Restaurant.find(
{name:{$regex:search,$options:"i"}},
{locality:{$regex:search,$options:'i'}},
{"cuisine.name":{$regex:search,$options:'i'})
I am getting an empty array as output, as I mentioned multiple fields together in .find()..
I am getting output if I use the below code(i.e) find only one field..
const Rest = await Restaurant.find({name:{$regex:search,$options:"i"}})
If I search for any of the 3 fields name/locality/cuisine.name I should get appropriate output.
2
Answers
Your original query was incorrect. Those conditions should be grouped into one parameter. It should be as below:
The above query will work the matching in AND conditions (all filter criteria must be fulfilled).
Instead, you need to work the query in OR conditions with the
$or
operator (either one of the filter criteria needed to be fulfilled).Solution
Demo @ Mongo Playground
You can look at $and operator and $or operator in Mongodb, You can use $and operator if you want to match all of the given parameters or $or operator if one must match. Like this:
See the documentation:
$and operator
$or operator