Search code examples
node.jsmongodbmongodb-queryaggregation-frameworkmongoose-schema

Mongodb find if document value is present as a substring


I have a collection of ORDERS which is like:

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

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

Then in my api i have data like

 cityInOrder='Mumbai City'

so how do i find out all the order from my ORDER collection which have order.city as a substring in "cityInOrder"

that means in my first collection city is 'Mumbai' so data i received is 'Mumbai City' so i should get this document returned

I tried like

db.collection('orders').find({
  city: {
    $regex: cityInOrder
  }
})

but seems this works the other way around :( and also it shouldnt be case sensitive


Solution

  • There are couple of problems.

    1. You are using regex option where you need a search use case.
    2. You are expecting case insensitive searches.

    You can do few things.

    1. If you need search use cases and you are using atlas, you can use search functionality of atlas.

    2. If you don't have atlas and you need to match this criteria, you can do as below.

    You can use i option of regex to avoid case sensitive. You have to split input words by space and make or request to match either Mumbai or city

    Trial demo

    I would suggest to use option 1. If it is only city and you need always first term to be matched, you can try with second option which is some hacks involved.