1

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?

4

2 回答 2

4

您每次都在搜索 2 种不同的东西。在终端中,您正在使用正则表达式搜索单词 phone 的出现。在您的应用程序中,您正在搜索字符串文字“/phone/”的出现。您还需要在应用程序的 mongodb 查询中进行正则表达式搜索:

var key = 'phone';
collection.find({"product":{ $regex: key }).toArray(function(err,result) ...
于 2013-02-12T10:36:19.523 回答
1
var key = 'phone';
var reg = RegExp('.*'+key+'.*','gi');
collection.find({"product":{ $regex: reg }).toArray(function(err,result){

}

如果您的密钥出现在字符串之间,这也将起作用

于 2013-02-14T07:23:11.323 回答