Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to lowercase field data in MongoDB find()

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading