Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query with like in MongoDB

How can I do a like query in MongoDB using Node.js?

Here's my source code, but it doesn't work:

exports.findAll = function(req, res) {
    var country=req.params.country; 
    db.collection('wines', function(err, collection) {
        collection.find({ 'country': new RegExp('/'+country+'/i') }).toArray(function(err, items) {
            res.jsonp(items);
        });
    });
};
like image 960
Alexander Ceballos Avatar asked Jun 27 '13 21:06

Alexander Ceballos


People also ask

WHAT IS LIKE operator in MongoDB?

If we want SQL like “Like” operator in Mongo DB for string matching. But in mongo DB there is no such “like” operator instead it has regular expression to achieve a similar feature.

How do I match a string in MongoDB?

MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language. Unlike text search, we do not need to do any configuration or command to use regular expressions.


1 Answers

I solved it like this:

 exports.findAll = function(req, res) {
        var country=req.params.country; 
        db.collection('wines', function(err, collection) {
            collection.find({ 'country': new RegExp(country, 'i') }).toArray(function(err, items) {
                res.jsonp(items);
            });
        });
    };
like image 115
Alexander Ceballos Avatar answered Sep 22 '22 00:09

Alexander Ceballos