Kaushik Lele
Kaushik Lele

Reputation: 6637

mongoDB query with case insensitive schema element

In my MongoDB collection I have added a record as follows

db.teacher.insert({_id:1 ,"name":"Kaushik"})

If I search

db.teacher.find({name:"Kaushik"})

I get one record. But if I try "NAME" instead of "name" i.e.

db.teacher.find({NAME:"Kaushik"})

It won't return any record.

It means that I must know how schema element is spelled exactly with exact case. Is there way to write query by ignoring case of schema element.

We can search the element value using case insensitive as follows

> db.teacher.find({name:/kAUSHIK/i})
{ "_id" : 1, "name" : "Kaushik" }

Is there similar for schema element; something like

> db.teacher.find({/NAME/i:"kaushik"})

Upvotes: 2

Views: 963

Answers (3)

Sylvain Leroux
Sylvain Leroux

Reputation: 52040

We can search the element value using case insensitive [...]

Is there [something] similar for schema element [?]

No.


We may assume that JavaScript and JSON are case sensitive, and so are MongoDB queries.

That being said, internally MongoDB uses BSON, and the specs say nothing about case-sensitivity of keys. The BNF grammar only said that an element name is a nul terminated modified UTF-8 string:

e_name      ::=     cstring            Key name
cstring     ::=     (byte*) "\x00"     Zero or more modified UTF-8 encoded
                                       characters followed by '\x00'. The
                                       (byte*) MUST NOT contain '\x00', hence
                                       it is not full UTF-8.

But, from the source code (here or here for example), it appears that MongoDB BSON's implementation use strcmp to perform binary comparison on element names, confirming there is no way to achieve what you want.

This might be indeed an issue beyond case sensitivity, as using combining characters, the same character might have several binary representations -- but MongoDB does not perform Unicode normalization. For example:

> db.collection.insert({"é":1})
> db.collection.find({"é":1}).count()
1
> db.collection.find({"e\u0301":1}).count()
0

Upvotes: 3

Aditya Chopra
Aditya Chopra

Reputation: 21

You could use a regex like

db.teacher.find({name:/^kaushik$/i})

Upvotes: -2

Himen
Himen

Reputation: 1450

This related to javascript engine and json specification. in js identifiers are case sensitive. This means you can have a document with two field named "name" and "Name" or "NAME". So mongodb act as two distinct filed with your fields.

Upvotes: 0

Related Questions