Home > Software design >  Finding document with regex but the input is array
Finding document with regex but the input is array

Time:11-01

I am trying to find solution for findig document with array search input. Solution on next line is working great, but i need to do more complex search.

const searchInput = ["United States","Mexico"]  
model.find({country: { $in: searchInput },})

The data has "country" field in various forms and for that reason i need to use regex. For which the following solution works if only one country is searched.

model.find({country : {$regex : "United States"}});

But I need to combine the previous two solutions. Do I need to do a separate search for each element in the array, or is there a better solution?

Example data:

0: {country: "United States"}
1: {country: "Mexico"}
2: {country: "Canada"}
3: {country: "United States | Canada"}

From these documents, I want to find only those that match the search equals ["United States","Mexico"].

Expected results:

0: {country: "United States"}
1: {country: "Mexico"}
3: {country: "United States | Canada"}

Thank you for any help

CodePudding user response:

You can use pipes instead of array, like this:

model.find({
  country: {
    $regex: "United States|Mexico"
  }
})

See how it works on the playground example.

Of course you can use an aggregation pipeline to build the string with pipes from the array, but I think it will be simpler and cleaner to do it in the code and use a simple find

  • Related