Home > OS >  How to make search query in mongoose to find only that "key" having value "singleWord
How to make search query in mongoose to find only that "key" having value "singleWord

Time:12-03

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;
    });

CodePudding user response:

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?

  • Related