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);
});
});
};
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.
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.
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);
});
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With