Ratnabh Kumar Rai
Ratnabh Kumar Rai

Reputation: 584

MongoDB using regex to query array of strings and find the document

I have a collection of ORDERS which is like:

_id:5f8e7d8084378609b2dca93f
user_id:"5f8465a777b1814c588521e2"
price:96
city:"Mumbai City"
totalCost:96

_id:5f8e7d8084378609b2dca93f
user_id:"5f8465a777b1814c588521e2"
price:96
city:"Delhi"
totalCost:96

Then in my API I receive data which is in form of array:

driverCity = ['Mumbai', 'Ahmednagar', 'Yavatmal', 'Warud', 'Umred']

Now how do I query my ORDERS collection and then check that ORDER.city is present as a substring is my driverCity variable by regex ? it means that if a substring like "mumbai" is present in ORDER.city and also in this array I want that result.

Upvotes: 0

Views: 192

Answers (2)

turivishal
turivishal

Reputation: 36114

Join array element with | and make a string, use $regex to get matching city,

let driverCity = ['Mumbai', 'Ahmednagar', 'Yavatmal', 'Warud', 'Umred'].join("|");
// "Mumbai|Ahmednagar|Yavatmal|Warud|Umred"

db.collection.find({
  city: {
    $regex: driverCity
  }
})

Playground

Upvotes: 1

Anuj Pancholi
Anuj Pancholi

Reputation: 1203

If you're querying from the MongoDb driver for Nodejs then you can make a case-insentitive regex query:


const driverCity = ['Mumbai', 'Ahmednagar', 'Yavatmal', 'Warud', 'Umred'];

db.collection("ORDERS").find({
    city: new RegExp(driverCity.map(city => `(${city})`).join('|'),'i')
})

NOTE: Regex queries in mongodb (or anywhere, really) are a bit heavy and can be slow and resource-intensive. I would recommend your city key in the ORDERS collection is indexed.

Upvotes: 2

Related Questions