Function for recursively searching in mongodb