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

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