I am trying to find data in mongodb. i am having data like this
{"name":"xxxx","product":"laptop,phone,mobile"}
{"name":"yyyy","product":"phone,iphone,pendrive"}
i am trying to find "phone" is in product key so i have tried this command in terminal
db.collection.find({"product": /phone/});
it is working fine but it is not working in my application.so i have tried dynamically like that in my application.
var key=phone;
var name="/"+key+"/";
collection.find({"product":name}).toArray(function(err,result)
{
console.log(result.length);
});
but i am always getting 0 length only so how to use that dynamically?
You're searching for 2 different things each time. In the terminal you're searching for occurrences of the word phone with a regular expression. In your application you are searching for occurrences of the string literal '/phone/'. You need to do a regex search in your mongodb query in your app as well:
var key = 'phone';
collection.find({"product":{ $regex: key }).toArray(function(err,result) ...
var key = 'phone';
var reg = RegExp('.*'+key+'.*','gi');
collection.find({"product":{ $regex: reg }).toArray(function(err,result){
}
if your key appears in between in the string also this will work