【问题标题】:mongodb regex searching issue in meteor流星中的mongodb正则表达式搜索问题
【发布时间】:2016-01-14 15:09:12
【问题描述】:

我的代码是

var search_element=Session.get("search_string");
var adc="/"+search_element+"*/";
console.log(adc);
return Polls_Coll.find({question:{$regex:adc}});

为什么它不起作用

如果我给了

Polls_Coll.find({question:{$regex:/Best*/}});

conslow 它正在工作,如果我用值(search_element)替换正则表达式,它就不起作用。我认为它正在像这样替换

Polls_Coll.find({question:{$regex:"/Best*/"}});(with quotes "/Best*/")

这是主要问题吗?还是我犯了什么愚蠢的错误??

【问题讨论】:

    标签: regex mongodb meteor


    【解决方案1】:

    有两种语法:

    Polls_Coll.find({question:/Best*/});
    

    Polls_Coll.find({question:{$regex:"Best*"}});
    

    您在每个中都使用了元素,所以这可能是它不起作用的原因。在 mongodb 文档中有更多详细信息:http://docs.mongodb.org/manual/reference/operator/query/regex/

    这两种形式在 Meteor 中都可以正常工作,所以你不应该对它们有任何问题。

    【讨论】:

    • 如果你清楚地注意到我的问题,我尝试了Polls_Coll.find({question:{$regex:"\Best*\"}}); 而不是这个Polls_Coll.find({question:{$regex:"Best*"}}); 任何方式谢谢你的回复,它正在工作
    • @sasikanth 正如对原始问题响应的评论,如果你能做到,请尝试使用插入符号从字符串的 开头 开始查看,例如“^Best *”。如果不这样做,您的查询将导致收集扫描以找到匹配项。对于需要匹配任何地方的大型数据,请考虑对内容进行标记,否则会遇到性能问题。
    • 感谢您的建议,另一个问题是如果我想在文档的所有字段中搜索字符串怎么办。您有什么想法吗,查询是什么样的
    • @sasikanth 您可以进行全文搜索:docs.mongodb.org/manual/core/index-text。不过,您也必须使用一些包来公开进行查询的方法(也仅限服务器端)
    【解决方案2】:

    我使用这种语法,它对我有用:

    Polls_Coll.find({ name: {$regex: "adc", $options: '-i'} });
    

    类似:

    SELECT * FROM Polls_Coll WHERE name LIKE '%adc%'
    

    我还使用https://atmospherejs.com/meteor/reactive-var 实现如下代码:

    if (Meteor.isServer) {
        Meteor.publish('customersSearch', function(searchValue){
            if (searchValue) {
                return Customers.find({ name: {$regex: searchValue, $options: '-i'} });
            }
       });
    }
    
    var searchQuery = new ReactiveVar();
    
    Template.NewRO.onCreated(function(){
        var self = this;
        self.autorun(function() {
            self.subscribe('vehicles');
            self.subscribe('customersSearch', searchQuery.get());
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多