Example:
> db.stuff.save({"foo":"bar"});
> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0
Example:
> db.stuff.save({"foo":"bar"});
> db.stuff.find({"foo":"bar"}).count();
1
> db.stuff.find({"foo":"BAR"}).count();
0
I've created a simple Func for the case insensitive regex, which I use in my filter.
Then you simply filter on a field as follows.
As of Mongodb 3.4 you should use a case-insensitive collation index. This is the fastest way to do a case-insensitive search over datasets of increasingly large size. I personally emailed one of the founders to please get this working, and he made it happen! (It was an issue on JIRA for like 5 years, and many have requested the feature). Here's how it works:
A case-insensitive index is made by specifying a collation with a strength of either 1 or 2. You can create a case-insensitive index like this:
Or you can do it for the whole collection by default when you create the database like so:
And use it like this:
This will return "New York", "new york", etc.
Alternatively, you can make all indexes use a collation by default when you make the collection like this:
The benefit to this method is much improved efficiency and speed on larger datasets.
For more info: https://jira.mongodb.org/browse/SERVER-90 , https://docs.mongodb.com/manual/reference/collation/
Using Mongoose this worked for me:
For any one using Golang and wishes to have case sensitive full text search with mongodb and the mgo godoc globalsign library.
The best method is in your language of choice, when creating a model wrapper for your objects, have your save() method iterate through a set of fields that you will be searching on that are also indexed; those set of fields should have lowercase counterparts that are then used for searching.
Every time the object is saved again, the lowercase properties are then checked and updated with any changes to the main properties. This will make it so you can search efficiently, but hide the extra work needed to update the lc fields each time.
The lower case fields could be a key:value object store or just the field name with a prefixed lc_. I use the second one to simplify querying (deep object querying can be confusing at times).
Note: you want to index the lc_ fields, not the main fields they are based off of.
Use RegExp, In case if any other options do not work for you, RegExp is a good option. It makes the string case sensitive.
The value of
uname
will be like/John/i
.use uname in queries instead of username, and then its done.
I hope it will work for you too. All the Best.