13

我正在使用来自 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>

顺便说一句,我发现完全匹配效果很好,但这不是我想要的。

IE。

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

2 回答 2

29

你几乎拥有它。除非您有一些看起来很奇怪的邮政编码,否则您会一直在字符串中使用正则表达式并寻找可以找到任何东西的字符串。 '/^94404/'

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

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

那么你就可以:

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

这种东西在 MongoDB shell 中有效,类似的东西在 Ruby 界面中有效,因此它也应该在 JavaScript 界面中有效。

于 2012-06-17T19:07:07.180 回答
10

$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'}})

不包含string

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

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

于 2015-11-28T11:40:18.860 回答