Tobias
Tobias

Reputation: 5108

Mongo query that's case insensitive regarding field name

Example:

db.stuff.save({"InnerDocument": {"Id":"123"}});
db.stuff.save({"InnerDocument": {"ID":"123"}});

Is it possible to achieve the following?

> db.stuff.find({"InnerDocument.id":"123"}).count();
2

Upvotes: 1

Views: 2552

Answers (2)

helmy
helmy

Reputation: 9517

It is not possible. You could do a $or query like:

db.stuff.find({$or:[{"InnerDocument.id":"123"}, {"InnerDocument.Id":"123"}, {"InnerDocument.ID":"123"}]}).count();

But that's pretty ugly. I'd suggest that you keep your data and your field nameing conventions clean and consistent so you don't have to do that.

Upvotes: 1

Moi Syme
Moi Syme

Reputation: 466

There is no easy way to do something like that. You can do it via map-reduce framework of mongodb. This is an example:

db.stuff.mapReduce(
function(){ 
    var  key = 'id';
    var  value_temp = '123';
    for (i in this['InnerDocument']){
      if (key === i.toLowerCase() && this['InnerDocument'][i] === value_temp){
            emit(key,1);
      }
    }

    },
function(key,value){
    return Array.sum(value);
    },
{out : {inline : 1}}
)['results'][0];

As mentioned here MongoDB case insensitive key search there is no operator for something like this.

Upvotes: 0

Related Questions