2

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! So my solution is pretty easy with let searchInputRegex = searchInput.join("|") and your find function!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.