Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB-如何在表达式中使用JavaScript变量?_Mongodb_Mongodb Query - Fatal编程技术网

MongoDB-如何在表达式中使用JavaScript变量?

MongoDB-如何在表达式中使用JavaScript变量?,mongodb,mongodb-query,Mongodb,Mongodb Query,如何将变量放入此表达式中?我试过了 var myVariable = 'something'; db.test.find({$where: "myVariable.match( ... )"}); 但我得到一个错误“myVariable未定义”。怎么做呢?您需要将变量放入本地的$where中,如下所示: db.test.find({“$where”:function(){ var myVariable=“某物”; 返回myVariable.match(…) } ); 我尝试了您刚才发布的内容

如何将变量放入此表达式中?我试过了

var myVariable = 'something';

db.test.find({$where: "myVariable.match( ... )"});

但我得到一个错误“myVariable未定义”。怎么做呢?

您需要将变量放入本地的
$where
中,如下所示:

db.test.find({“$where”:function(){
var myVariable=“某物”;
返回myVariable.match(…)
}
);

我尝试了您刚才发布的内容。没有出现任何错误。您能详细说明一下吗?如果您想这样做,您需要使用$eval将变量放入函数范围注意:通常不鼓励使用,因为JavaScript求值不能利用索引。如果您可以包含示例文档和实际查询的示例如果您正在尝试构造,则可能有更高性能的替代方案可供推荐。@stennie我不确定是否有。
{$where:“myVariable.match(new RegExp(this.test+'$)”)
。如果
myVariable='something'
,它应该获得与结束子字符串匹配的文档,例如,
mething
thing
ing
。您可以使用