Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do a contains query using the MongoDB node.js driver?

I'm trying to do a search on items that contain a certain substring, but I'm getting no results back (even though I know the data is right for the query, including case):

collection.find({name: "/.*" + keyword + ".*/"}).toArray(function(err, items)

Should that not match everything that contains the keyword? It just returns an empty object.

I'm just using the regular MongoDB driver in an ExpressJS app.

like image 814
Mike Pateras Avatar asked Aug 30 '12 07:08

Mike Pateras


2 Answers

You need to build a regular expression first should try something like this:

var regex = RegExp("/.*" + keyword + ".*/")

Then pass in the variable to the query. I generally find it easier to do the query as a variable and pass that in:

var query = { FieldToSearch: new RegExp('^' + keyword) };
collection.find(query).toArray(...)

I've included the regex as a left rooted regex to take advantage of indexes (always recommended if possible for performance). For more take a look here:

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

like image 52
Adam Comerford Avatar answered Sep 19 '22 19:09

Adam Comerford


I did it like this

    keyword = "text_to_search";
    collection.find({name: {$Regex: keyword, $options:$i }})

I used i $i make the query case insensitive but u can use other options too

like image 25
Muhammad Fayyaz Avatar answered Sep 20 '22 19:09

Muhammad Fayyaz