Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Regular Expression Search - Starts with using javascript driver and NodeJS

I'm using the JavaScript mongodb driver from nodejs. I want to do this query in my JavaScript function:

db.mycollection.find({Zip:/^94404/}); 

The mongo client retrieves 8 docs that match this criteria. However my JavaScript code does not fetch any documents.


    DataProvider.prototype.findByZipcode = function(zipCode, callback) {
        this.getCollection(function(error, collection) {
            if (error)
                callback(error);
            else {
                var qs = '{Zip:/^'+zipCode+'/}';
                collection.find(qs).toArray(function(error, results) {
                    if (error)
                        callback(error);
                    else
                        callback(null, results);
                });
            }
        });
    };

I also tried

<pre>
var qs = {Zip: '/^'+zipCode+'/'};
</pre>

Btw, I find exact match works fine, but that's not what I want.

ie.

<pre>
var q = {'Zip' :zipCode};
</pre>
like image 630
user1462193 Avatar asked Jun 17 '12 18:06

user1462193


2 Answers

You almost have it. You keep ending up with a regex inside a string and looking for the string '/^94404/' going to find anything unless you have some strange looking zip codes.

The easiest way to build a regex object from a string in JavaScript is to use new RegExp(...):

var query = { Zip: new RegExp('^' + zipCode) };

Then you can:

collection.find(query).toArray(...)

That sort of thing works in the MongoDB shell and similar things work in the Ruby interface so it should work in the JavaScript interface as well.

like image 134
mu is too short Avatar answered Oct 17 '22 09:10

mu is too short


$options => i for case insensitive search

Start with string

db.collection.find({zip:{'$regex' : '^string', '$options' : 'i'}})

End with string

db.collection.find({zip:{'$regex' : 'string$', '$options' : 'i'}})

Contains string

db.collection.find({zip:{'$regex' : 'string', '$options' : 'i'}})

Doesn't Contains string

db.collection.find({zip:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

Keep this as a bookmark, and a reference for any other alterations you may need. http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

like image 25
Somnath Muluk Avatar answered Oct 17 '22 08:10

Somnath Muluk