说我在MongoDB集合中有以下文档:
{
"recipeName": "barbecued chicken",
"author_id": "123"
}
{
"recipeName": "grilled steak",
"author_id": "123"
}
{
"recipeName": "pork and beans",
"author_id": "444"
}
{
"recipeName": "gravy",
"author_id": "333"
}
{
"recipeName": "corn chowder",
"author_id": "222"
}
{
"recipeName": "pork roast",
"author_id": "543"
}
然后,我在javascript中有这个数组:
["grilled steak", "baked steak", "smothered steak"]
我想看看我的数组中的任何值是否与任何文档的recipeName匹配(在这种情况下,烤牛排会匹配)。然后,我想获取匹配文档的author_id。
我意识到我可以查询数组中每个项目的recipeName,但是有更有效的方法吗?这个数组可能很大(这将是很多查询)。我可以一次检查我的数组中的所有项目吗?如果我得到匹配,请将author_id返回给我?
这只是一个例子,而不是实际数据:P。提前感谢任何建议。
我目前在循环中有这个,但我正在寻找一种更有效的方式......
mongo.connect(uristring, function (err, db) {
db.collection("recipes", function(err, collection) {
if (!err) {
collection.findOne({
'recipeName': recipeName
}, function (err, href) {
if (err) {
return false;
}
if (!href) {
return false;
}
return true;
});
} else {
console.log(5, 'DB error');
}
});
});
答案 0 :(得分:0)
您可以使用$in
运算符:
collection.findOne({
recipeName: { $in: ["grilled steak", "baked steak", "smothered steak"] }
}, function (err, href) { ... });