Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding document with regex but the input is array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading