skip to Main Content

I’m having one query to do indepth search for a regex in mongoDB. I’m using JS function inside the query like this –

db.collection.find(
        {$where: function() {
        function  deepIterate(obj, value) {
        var new_value = new RegExp("^"+value, "i");
        for (var field in obj) {
            if (obj[field] == new_value){
                return true;
            }
            var found = false;
            if ( typeof obj[field] === 'object' ) {
                found = deepIterate(obj[field], new_value)
                if (found) { return true; }
            }
        }
        return false;
    };
    return deepIterate(this, "[A-Ba-b0-9]*60.51[A-Ba-b0-9]*")
}}
)

It doesn’t return any values, output is Fetched 0 record(s) in 4ms. But I’m having one string in my database – 192.108.60.51. That record is not getting returned.
Help!!!

2

Answers


  1. Chosen as BEST ANSWER

    Found out the solution -

    db.collection.find({$where: function() {
            function  deepIterate(obj, value) {
            new_value = new RegExp(value, 'i');
            for (var field in obj) {
                if (new_value.test(obj[field])){
                    return true;
                }
                var found = false;
                if ( typeof obj[field] === 'object' ) {
                    found = deepIterate(obj[field], new_value)
                    if (found) { return true; }
                }
            }
            return false;
        };
        return deepIterate(this, "[A-Ba-b0-9]*60.51[A-Ba-b0-9]*")
    }})
    

  2. You can change your regex pattern into deepIterate(this, "(([1-9]?\d|1\d\d|2[0-5][0-5]|2[0-4]\d)\.){3}([1-9]?\d|1\d\d|2[0-5][0-5]|2[0-4]\d)$") this regex is for find string that is an Ip-Address. You can’t find any record because your regex pattern not match with your record in database

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search