Home > Net >  How to lowercase field data in MongoDB find()
How to lowercase field data in MongoDB find()

Time:11-10

In my database collection I have two Objects.

[
  {"_id" : 1, name: "notLowercased"},
  {"_id" : 2, name: "lowercased"},
]

I'm using find and $regex to find name that includes some string.

data = await CatalogModel.find({name: {$regex : searcher.toString().toLowerCase()}})

For example my input string is "lowercased".

In result I'm getting an array

[
  {"_id" : 2, name: "lowercased"},
]

But I want to get in result this:

[
  {"_id" : 1, name: "notLowercased"},
  {"_id" : 2, name: "lowercased"},
]

I'm understand that it's happening becase name "notLowercased" not lowercased.

How to lowercase name fields in this request?

CodePudding user response:

You can add $options parameter like this: $options: "i".

As explained into docs:

i: Case insensitivity to match upper and lower cases. For an example, see Perform Case-Insensitive Regular Expression Match.

Even you can avoid toLowerCase()

data = await CatalogModel.find({name: {$regex : searcher.toString(), "$options": "i" }})

Example here and without toLowerCase() here

  • Related