MongoDB正则表达式搜索 - 从使用javascript驱动程序和NodeJS开始 [英] MongoDB Regular Expression Search - Starts with using javascript driver and NodeJS

查看:116
本文介绍了MongoDB正则表达式搜索 - 从使用javascript驱动程序和NodeJS开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用nodejs的JavaScript mongodb驱动程序。我想在我的JavaScript函数中执行此查询:

I'm using the JavaScript mongodb driver from nodejs. I want to do this query in my JavaScript function:

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

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

The mongo client retrieves 8 docs that match this criteria. However my JavaScript code does not fetch any documents.



    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>

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

Btw, I find exact match works fine, but that's not what I want.

即。

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


推荐答案

你几乎拥有它。你一直在一个字符串中的正则表达式结束,并寻找字符串 '/ ^ 94404 /'除非你有一些奇怪的东西才能找到任何东西查看邮政编码。

You almost have it. You keep ending up with a regex inside a string and looking for the string '/^94404/' going to find anything unless you have some strange looking zip codes.

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

The easiest way to build a regex object from a string in JavaScript is to use new RegExp(...):

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

然后你可以:

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

那有些东西在MongoDB shell中工作,类似的东西在Ruby界面中工作,所以它也可以在JavaScript界面​​中工作。

That sort of thing works in the MongoDB shell and similar things work in the Ruby interface so it should work in the JavaScript interface as well.

这篇关于MongoDB正则表达式搜索 - 从使用javascript驱动程序和NodeJS开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆