Reputation: 1679
I'm using mongodb in javascript and I was wondering how to effectively query names in a collection. As it is, I have 2 fields for my collections for the same thing which is pretty reduntent.
queryName: String
and name: String
The reason I do this is because if I have the name "John" for name, and I try try query the collection for the name "john"(note how the j is lowercase). It will return null. That's why I have the field queryName that takes the name and puts it into a format that's searchable. I was wondering if there's an option to disable case sensitivity and getting rid of spaces?
Upvotes: 1
Views: 130
Reputation: 5198
Use regex:
db.collection.find({name: /^john$/i });
Not sure what you mean when explaining why you have queryName
and name
, unless the former is some sort of normalization of the name
field.
If you want to get rid of spaces, you'll have to be more specific. Spaces surrounding the query? Spaces in-between characters? You can do either with regex, though the latter is more cumbersome. A common practice is to trim()
your data before you store it, though, so you don't have this problem.
db.collection.find({name: /^\s*john\s*$/i });
I'll leave it to OP to modify use for more complicated white space handling.
Upvotes: 1