如何找到键值对特定的字符串MongoDB中
我有MongoDB中的数据一样,如何找到键值对特定的字符串MongoDB中
[
{
"name":"silvester",
"product":"laptop,iphone,mobile,phone"
},
{
"name":"john",
"product":"cycle,bus,phone,laptop"
},
{
"name":"franklin",
"product":"cycle,phone"
}
]
如何找到那台笔记本电脑在产品密钥。 如果这样
{
"name":"XXX",
"product":"laptop"
}
我可以很容易地找到使用该db.collection.find("product":"laptop");
该名称的产品密钥看起来那么如何找到呢?
另外让我知道这三个网站名称运行使用backbone.js和node.js和mongodb技术,如www.trello.com。 对不起我的英语最差..
这为我工作
db.collection.find({ “产品”:/笔记本/})
更新回答
如果您想使用变量,请尝试如下所示:
var abc = "laptop";
// other stuff
userdetails.find({"product":new RegExp(abc)}).toArray(function(err,result){
if (err) console.log ("error: "+err);
else
{
// if you want the length
console.log(result.length);
// if you actually want to see the results
for (var i = 0; i < result.length; i++)
{
console.log(result[i]);
}
}
});
更新再来一次
var abc = "laptop";
// other stuff
// note this is case sensitive. if abc = "Laptop", it will not find it
// to make it case insensitive, you'll need to edit the RegExp constructor
// to this: new RegExp("^"+abc+",|, "+abc+"(?!\w)", "i")
userdetails.find({"product":new RegExp("^"+abc+",|, "+abc+"(?!\w)")}).toArray(function(err,result){
if (err) console.log ("error: "+err);
else
{
// if you want the length
console.log(result.length);
// if you actually want to see the results
for (var i = 0; i < result.length; i++)
{
console.log(result[i]);
}
}
});
非常感谢你... – silvesterprabu 2013-02-11 16:31:57
我宁愿改变架构以使产品领域成为一个字符串数组,这将使你能够使用这个领域的索引并显着提高你查询的性能。就像现在的版本一样,你将每次都浏览整个系列。 – vittore 2013-02-11 17:14:14
我已经给出了这个动态像这样var abc = laptop; userdetails.find({ “产品”: “/” + ABC + “/”})。指定者(功能(ERR,结果){的console.log(result.length)});但我只有零长度,所以如何动态地做到这一点? – silvesterprabu 2013-02-12 07:44:30
正则表达式将工作完全正常。也有好消息告诉你的monogdb将在即将到来的版本
http://docs.mongodb.org/manual/release-notes/2.4/#text-indexes
是“产品”数组或字符串或逗号分隔的元素被释放全文搜索索引? – randunel 2013-02-11 15:51:40
下面发布的解决方案不适合你吗? – thtsigma 2013-02-11 16:16:21
您应该将'product'作为一串字符串存储,因为Mongo针对这种情况进行了优化。其他任何事情都会慢得多。 – 2013-02-11 16:28:56