0

I am working on a moongoose app and facing issue to search the data having single val in string

e.g.

Data :[
        { "name": "Shubham"},
        {"name":"Shubham Sharma"},
        {"name":"Sharma"}
      ]

Search result for "Shubham" should be

[
    { "name": "Shubham"}
]

Using this query I am not able to achieve my goal

var regexp = new RegExp(`^${name.toLowerCase()}`);
 let promise = await usersModel.find({ name: regexp }).limit(40)
.collation({ locale: "en", caseLevel: true })
    .exec(async function (err, users) {
        if (err) {
          return users;
        }})
      throw err;
    });
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • your regex matches every string that starts with `name.toLowerCase()` you probably want to add a `$` to the end to indicate that the string has to finish after that. Is there a specific reason why you use a regex? why can't you simply go with `{name: name.toLowerCase()}` – mmoehrlein Dec 01 '22 at 07:50

1 Answers1

0

By using $regex within your query, and enabling the i option for case insensitive matching, you shouldn't need to transform your input string at all.

Example playground - https://mongoplayground.net/p/tHap2kGneOa

Query:

db.collection.find({
  name: {
    $regex: "^Shubham$", // ^ = Starts with. $ = Ends with
    $options: "i" // i = case insensitive
  }
})

Which will match:

Shubham
shubham

but not:

Sharma Shubham
Sharma
Shubham Sharma

Update - Based on comments.

Note: In this instance of case insensitive absolute string matching, you could also take advantage of collations - MongoDB: Is it possible to make a case-insensitive query?

dangarfield
  • 2,210
  • 1
  • 13
  • 18
  • Btw thank you so much for telling me about $options. it will really going to help me. I am new to mongoose, i know only basics. – Shubham Sharma Dec 01 '22 at 17:21
  • I want to omit last result from here only need shubham/Shubham in results – Shubham Sharma Dec 01 '22 at 17:22
  • So, you want it to be case insensitive, but ONLY match the whole of the string? if `Shubham` should match ONLY `Shubham` and `shubham`. Is that right? If that is the case, just add a `$` at the end of the string, eg `^Shubham$` - Example - https://mongoplayground.net/p/tHap2kGneOa – dangarfield Dec 01 '22 at 17:30
  • Thank you its working fine now ! i am marking this as an answer, also edited as you mentioned in comment to add `$` – Shubham Sharma Dec 02 '22 at 18:51