You are correct in a certain statement of a BSON document, it is not an XML document. Because XML is loaded into a tree structure made up of "nodes", searching by a stern key is fairly straightforward.
A MonoDB document is not easy to process, and in many ways it is a "database", so it is expected that it will have a certain "uniformity" of data locations in order to simplify the "indexing" and search.
However, this can be done. But of course, this means that a recursive process is running on the server, and this means that JavaScript is processed using $where .
As a basic shell example, but a generic function is just a string argument to the $where operator everywhere:
db.collection.find( function () { var findKey = "find-this", findVal = "please find me"; function inspectObj(doc) { return Object.keys(doc).some(function(key) { if ( typeof(doc[key]) == "object" ) { return inspectObj(doc[key]); } else { return ( key == findKey && doc[key] == findVal ); } }); } return inspectObj(this); } )
So, basically, check the keys present in the object to see if they match the desired โfield nameโ and contents. If one of these keys is an โobjectโ, then go to the function and check again.
JavaScript .some() ensures that the match found is returned from the search function, giving the result true and returning the object where this key / value was present at some depth.
Note that $where essentially means moving your entire collection if there is no other valid query filter that can be applied to the "index" in the collection.
So use with caution or donโt work at all and just work with restructuring the data into a more usable form.
But it will give you your match.
Blakes seven
source share