skip to Main Content

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


  1. Chosen as BEST ANSWER

    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


  2. 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 = db.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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search