use*_*193 12 javascript regex mongodb node.js
我正在使用nodejs的JavaScript mongodb驱动程序.我想在我的JavaScript函数中执行此查询:
db.mycollection.find({Zip:/^94404/});
Run Code Online (Sandbox Code Playgroud)
mongo客户端检索8个符合此条件的文档.但是我的JavaScript代码不能获取任何文档.
DataProvider.prototype.findByZipcode = function(zipCode, callback) { this.getCollection(function(error, collection) { if (error) callback(error); else { var qs = '{Zip:/^'+zipCode+'/}'; collection.find(qs).toArray(function(error, results) { if (error) callback(error); else callback(null, results); }); } }); };
我也试过了
<pre>
var qs = {Zip: '/^'+zipCode+'/'};
</pre>
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我发现完全匹配工作正常,但这不是我想要的.
即.
<pre>
var q = {'Zip' :zipCode};
</pre>
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 28
你几乎拥有它.除了你有一些看起来很奇怪的邮政编码之外,你最终会在字符串 '/^94404/'
中找到一个正则表达式并查找要查找的字符串.
从JavaScript中的字符串构建正则表达式对象的最简单方法是使用new RegExp(...)
:
var query = { Zip: new RegExp('^' + zipCode) };
Run Code Online (Sandbox Code Playgroud)
然后你可以:
collection.find(query).toArray(...)
Run Code Online (Sandbox Code Playgroud)
这种东西在MongoDB shell中工作,类似的东西在Ruby接口中工作,所以它也应该在JavaScript接口中工作.
$options => i
用于不区分大小写的搜索
从...开始 string
db.collection.find({zip:{'$regex' : '^string', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)
结束 string
db.collection.find({zip:{'$regex' : 'string$', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)
包含 string
db.collection.find({zip:{'$regex' : 'string', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)
不包含 string
db.collection.find({zip:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)
将此作为书签,以及您可能需要的任何其他更改的参考. http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/