Edgar
Edgar

Reputation: 927

MongoDB - search in document's nested objects

I have documents in my collection similar to foo. These documents can have a nested parent object which also can have a nested parent object and so on..

foo: {
    caption: "Italian",
    code: "",
    id: 17,
    parent: {
       caption: "Restaurants",
       code: "",
       id: 9,
       parent: {
          caption: "Food and Drink",
          code: "food_and_drink",
          id: 1,
          parent: ""
      }
   }
};

How can I search for a mathch in foo.parent.id and all it's nested parent objects (if there are any)? Should I use $in? Recursively?

Upvotes: 0

Views: 321

Answers (2)

Parshuram Kalvikatte
Parshuram Kalvikatte

Reputation: 1636

Yes you have to use recursion,Below code will be very helpfull to you,try this

    db.getCollection('foo').find().
      forEach(function(x) {
          function t(x){
               if (x.parent) {
                 t(x.parent);
               } else {
                 print(x.caption);
               }
         } 
         t(x)
     });

You will get the last parent of all document and get any field of that parent instead of caption I have used caption

If above code doesnt work put a small change

if(x.parent != "") instead of if(x.parent)

Upvotes: 0

Orelsanpls
Orelsanpls

Reputation: 23495

You can give to the method find(...) a custom function that's gonna check for you the nested levels.

Example

 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);
  }
)

To look at

StackOverflow: How to find MongoDB field name at arbitrary depth

Upvotes: 1

Related Questions