Find documents in MongoDB where one element or elements in array field matches an element in other array

127 Views Asked by At

The query I've got so far:

const cities = await City.find({ names :  { $in: citiesArray }})

The field names are a String separated by commas (e.g "A, B, C, D, E...")
The field citiesArray is a array (e.g. ["A", "B", "C", "D", "E", ...])

How can I change this code to, let's say, return all documents that contain the first element in the names field 'A'. That would do, of course, if any elements from the array match any of the elements from the string field names, which could be useful later, but for now, matching the first element will be enough.

2

There are 2 best solutions below

0
On BEST ANSWER

You can map the array and generate a new Regex from each value in it:

const citiesArray = ["A", "B", "C", "D", "E", ...];

const mapToRegex = array => array.map(val => new RegExp(val, 'i'));
const cities = await City.find({ names: { $in: mapToRegex(citiciesArray) } });

Or you can use the pipe-delimited | regex pattern:

const citiesArray = ["A", "B", "C", "D", "E", ...];
const cities = await City.find({ names: { $regex: match.join("|"), $options: 'i' }});

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

0
On

The only solution I could find is this:

const city = await City.findById({_id: req.params.id})
const names = city.cities.split(",")
const first = names[0]
const cities = await City.find({ names: new RegExp(first, 'i') })

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