Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct node js MongoDB case insensitive

I am using distinct in Mongo to return some values in the Jquery Autocomplete like this:

function Reg(title)
    {
        this.title= title;
    }

exports.find = function(req, res) {
var b=req.params.search;
var query = new Array();
var cadsrch = b.split(' ');
var l = cadsrch.length;
var i = 0;
        for (i = 0; i < l; i++) {
            if(cadsrch[i]!=''){
              query[i]=new RegExp('^'+cadsrch[i], 'i');
            }
        }

var data=new Array();
        db.collection('publication', function(err, collection) {
                collection.distinct('title',{content:{'$all':query}},{'$or':[{type:'an'},{type:'pub'}]},
                  function(err, items) {
                         var l=items.length,i=0;
                         for (i=0;i<l;i++){
                            data[i]=new Reg(items[i]);
                         }
                         res.jsonp(data);
                         }
                )
        });
};

The problem is that the columns 'title' is working in case sensitive, I mean for example car is different to Car, I don't know if there is a way to avoid this and take Car the same as car

like image 914
Alexander Ceballos Avatar asked Aug 20 '13 14:08

Alexander Ceballos


2 Answers

I just saw this question and I know it has been answered however, for future reference, there was, and is, a "$downcase"; it is called $toLower http://docs.mongodb.org/manual/reference/aggregation/toLower/#exp._S_toLower

db.c.aggregate([
    {$group:{_id:{$toLower:'$title'}}}
]);

There is a problem though, you cannot SEARCH by case insenstive until case insensitive indexes are implemented: https://jira.mongodb.org/browse/SERVER-90 . This means currently you would have to searech by case insensitive regex as you do currently.

like image 159
Sammaye Avatar answered Sep 27 '22 22:09

Sammaye


That is a brilliant case for a "$downcase" operator in MongoDB's aggregation framework; yet, at this time, it does not exist.

The best you can do is store a searchable, downcased version of title for every document. Thus, your schema would look like:

{
  title: "War and Peace",
  searchable_title: "war and peace"
}

Your query logic would downcase the values prior to querying for the searchable title. For scale, stay away from case insensitive regexes, and go with downcased titles.

like image 33
Chris Winslett Avatar answered Sep 27 '22 23:09

Chris Winslett