Home > other >  How to search and find multiple field values... using MongoDB and I tried with regex
How to search and find multiple field values... using MongoDB and I tried with regex

Time:10-16

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.

CodePudding user response:

Your original query was incorrect. Those conditions should be grouped into one parameter. It should be as below:

const Rest = await Restaurant.find({
  name: {
    $regex: search,
    $options: "i"
  },
  locality: {
    $regex: search,
    $options: "i"
  },
  "cuisine.name": {
    $regex: search,
    $options: "i"
  }
})

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

const Rest = await Restaurant.find({
  $or: [
    {
      name: {
        $regex: search,
        $options: "i"
      }
    },
    {
      locality: {
        $regex: search,
        $options: "i"
      }
    },
    {
      "cuisine.name": {
        $regex: search,
        $options: "i"
      }
    }
  ]
})

Demo @ Mongo Playground

CodePudding user response:

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:

const Rest = await Restaurant.find({
  $and: [
    { name: { $regex: search, $options: "i" } },
    { locality: { $regex: search, $options: "i" } },
    { "cuisine.name": { $regex: search, $options: "i" } },
  ],
});

See the documentation:

$and operator

$or operator

  • Related