Is there an inbuilt way to search the field names using regex in a MongoDB database? The documentation lists a $regex field to search the field value.
You can do this either at arbitrary depth using JavaScript evaluation of a $where
clause:
db.collection.find(
function () {
var findKey = new RegExp("^start");
function inspectObj(doc) {
return Object.keys(doc).some(function(key) {
if ( typeof(doc[key]) == "object" ) {
return inspectObj(doc[key]);
} else {
return findKey.test(key);
}
});
}
return inspectObj(this);
}
)
Or if you have MongoDB 3.4 and are only looking at the "top" level of the document you could do this with .aggregate()
and $objectToArray
:
db.collection.aggregate([
{ "$addFields": {
"finder": { "$objectToArray": "$$ROOT" }
}},
{ "$match": { "finder.k": /^start/ } }
])
This is because $objectToArray
takes an "object" and translates into an array of objects with keys "k"
and "v"
for each "key" and "value" of the supplied object. We can do this to the entire document using $$ROOT
. So we are basically turning the "keys" into "data" that can be searched.
With the data transformed, you can then use simple "dot notation" and a regular $regex
query expression to match the value of the "key".
So the aggregate method is best for "flat" documents, or dealing with a "known depth", and the JavaScript approach is best where the key could be nested at any level.
Attribution to : How to find MongoDB field name at arbitrary depth for the essential parts of the JavaScript version of the search. Only modified for the regular expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With