The query I’ve got so far:
const cities = await City.find({ names : { $in: citiesArray }})
The field names is a String separated by commas (e.g "A, B, C, D, E…")
The field citiesArray is a JS array (e.g. ["A", "B", "C", "D", "E", …])
How can I change this code to, let say, return all documents that contains the first element in names field (‘A’). That would do, of course, if any elements from array matches any of elements from the string field names, could be useful later, but for now, matching the first element will be enough.
2
Answers
The only solution I could find is this:
It solves if I must match only the first value from the first array (from field cities). But this is not a good solution if later I try to expand to match all fields from first field of strings (separated by commas) and an array of itens
You can map the
array
and generate anew Regex
from each value in it:Or you can use the pipe-delimited
|
regex pattern:I created a demo here with more examples that include the results for both ways to explain it better: Demo Link
Also, here is the documentation: MongoDB Regex