arraysstringmongodbmongoosemultiple-matches

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


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.


Solution

  • 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