我在 mongodb 中有这样的数据
[
{
"name":"silvester",
"product":"laptop,iphone,mobile,phone"
},
{
"name":"john",
"product":"cycle,bus,phone,laptop"
},
{
"name":"franklin",
"product":"cycle,phone"
}
]
如何查找产品 key 中的笔记本电脑。 如果产品 key 看起来像这样
{
"name":"XXX",
"product":"laptop"
}
我可以使用这个 db.collection.find("product":"laptop"); 轻松找到该名称
那么如何找到这个呢?
同时让我知道这三个使用backbone.js和node.js以及mongodb技术运行的网站名称,例如www.trello.com。 抱歉我的英语最差..
最佳答案
这对我有用
db.collection.find({"product":/laptop/})
更新答案
如果您想使用变量,请尝试以下操作:
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]);
}
}
});
关于node.js - 如何在mongodb中查找键值对中的特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14815621/