Arjun
Arjun

Reputation: 165

How to search for a specific dynamic pattern of a field's in mongodb.?

I need to search mongodb collection for a specific pattern field. I tried using {$exists:true}; However, this gives results only if you provide exact field.

I tried using {$exists:true} for my field. But this does not give results if you give some pattern.

{
"field1":"value1",
"field2":"value2",
"field3":object
{/arjun1/pat1: 1,
/arjun2/pat2: 3,
/arjun3/pat3: 5
}
"field4":"value4",
}

From some field, I get the keys pat3 & field3. From this I would need to find out if the value /arjun3/pat3 exists in the document. If I use {"field3./arjun3/pat3":{$exists:true}}, this would give me results. But the problem is I get only field3 and pat3 and I need to use some pattern matching like field3.*.pat3 and then use $expr or $exists; which I'm not exactly sure how to. Please help.

Upvotes: 0

Views: 95

Answers (2)

Priyanka Kariya
Priyanka Kariya

Reputation: 181

you could try something of this kind

db.arjun.find(
    {"field3" : {
        "$elemMatch" : { $and: [
            {"arjun3.pat3" : {$exists:true}},
            {"arjun3.pat3" : 5}
        ]
        }}}
);

Upvotes: 1

Vasu Deo.S
Vasu Deo.S

Reputation: 1850

You can either go for regex (re module) for SQL like pattern matching, and compile your own custom wildcard. But if you don't want that then you can simple use the fnmatch module, it is a builtin library of python which allows wildcard matching for multiple characters (via*) or a single character (via ?).

import fnmatch

a = "hello"
print(fnmatch.fnmatch(a, "h*"))

OUTPUT:-

True

Upvotes: 1

Related Questions