0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

and how do i do the other way around?? i mean if driverCity='Mumbai City' and order have city 'Mumbai' just curious :)
1

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

2 Comments

cool and how do i do the other way around?? i mean if driverCity='Mumbai City' and order have city 'Mumbai'
mongoplayground.net/p/yUv4wUU6G5z here is the link i played with it but seems the other way isnt working :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.