How do I specify a document key's value as Regex expression to find a document in MongoDB?

Suppose I have multiple fields in a document whose key value I don’t know(only the user who has added the keys know that)

Now suppose user wants to finds a document specifying the key value, but he forgot what his key value was EXACTLY

So say I have this document:

name: "John Doe"
class: 5
MisChief: "Bullying"

where the MisChief key was custom created.

Suppose user wants to search for mischief: "bullying"

I can use $regex operator(or pattern; regex object) to search for the value, but how can I specify the key as a regex expression ?

I want to do something like this:

/mischief/i : /bullying/i

But the field value isn’t being accepted as a regex expression(I used compass to test it)

Another way to do this is to return all documents, and doing a case insensitive search for the keys from all those documents which is very inefficient.

You can search the keys of a document in MongoDB. This is using an aggregation query and using the $objectToArray operator. Here’s how:

Consider input documents:

{ "name" : "John Doe", "class" : 5, "mischief" : "Bullying" }
{ "name" : "Jane", "class" : 2, "plays" : "Hop scotch" }

The query:

db.test.aggregate([ 
  { 
      $addFields: { 
          doc: { $objectToArray: "$$ROOT" } 
      } 
  }, 
  { 
      $match: { 
          "doc.k": /^mis/i, 
          "doc.v": /bull/i 
      } 
  } 
])
2 Likes

Thanks for the link to $objectToArray. I did not know this operator yet.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.