0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.