Home > other >  Case insensitive search in mongodb?
Case insensitive search in mongodb?

Time:10-04

I know this question is already been asked by many other people. Many of the solutions were suggesting to use Regular expression. I want to know is there any other ways because using regular expression slows down the query result?

For example, If I have a student table in SQL like

id name
 1 vicky

Since SQL is case insensitive SELECT NAME FROM STUDENT WHERE NAME="vicky" or SELECT NAME FROM STUDENT WHERE NAME="VICKY" or SELECT NAME FROM STUDENT WHERE NAME="Vicky" would return same result.

Whereas in mongodb if I have a student document like:

{
    _id:ObjectId("something"),
    name:"Vicky"
}

db.student.find({name:"vicky"}) will return no result.

CodePudding user response:

db.collection.find( { "name" : { $regex : /vicky/i } } )

CodePudding user response:

use $regex

db.collection.find({
  name: {
    $regex: "Vicky",
    $options: "i"
  }
})

mongoplayground

  • Related