【问题标题】:MongoDB Regular Expression Search - Starts with using javascript driver and NodeJSMongoDB 正则表达式搜索 - 从使用 javascript 驱动程序和 NodeJS 开始
【发布时间】:2012-06-17 18:41:16
【问题描述】:

我正在使用来自 nodejs 的 JavaScript mongodb 驱动程序。我想在我的 JavaScript 函数中做这个查询:

db.mycollection.find({Zip:/^94404/}); 

mongo 客户端检索 8 个符合此条件的文档。但是我的 JavaScript 代码没有获取任何文档。

DataProvider.prototype.findByZipcode = function(zipCode, callback) { this.getCollection(函数(错误,集合){ 如果(错误) 回调(错误); 别的 { var qs = '{Zip:/^'+zipCode+'/}'; collection.find(qs).toArray(function(error, results) { 如果(错误) 回调(错误); 别的 回调(空,结果); }); } }); };

我也试过

<pre>
var qs = {Zip: '/^'+zipCode+'/'};
</pre>

顺便说一句,我发现完全匹配工作正常,但这不是我想要的。

即。

<pre>
var q = {'Zip' :zipCode};
</pre>

【问题讨论】:

    标签: javascript regex node.js mongodb


    【解决方案1】:

    你几乎拥有它。你不断地在一个字符串中找到一个正则表达式并寻找 string '/^94404/' 会找到任何东西,除非你有一些看起来很奇怪的邮政编码。

    在 JavaScript 中从字符串构建正则表达式对象的最简单方法是使用new RegExp(...)

    var query = { Zip: new RegExp('^' + zipCode) };
    

    那么你可以:

    collection.find(query).toArray(...)
    

    这种东西在 MongoDB shell 中工作,类似的东西在 Ruby 界面中工作,所以它也应该在 JavaScript 界面中工作。

    【讨论】:

      【解决方案2】:

      $options =&gt; i 用于不区分大小写的搜索

      string开头

      db.collection.find({zip:{'$regex' : '^string', '$options' : 'i'}})
      

      string结尾

      db.collection.find({zip:{'$regex' : 'string$', '$options' : 'i'}})
      

      包含string

      db.collection.find({zip:{'$regex' : 'string', '$options' : 'i'}})
      

      不包含string

      db.collection.find({zip:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})
      

      将此作为书签保存,并作为您可能需要的任何其他更改的参考。 http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-16
        • 2012-12-11
        相关资源
        最近更新 更多