'Recursively finds all db references to be dereferenced
:param items: The iterable (dict, list, queryset)
:param depth: The current depth of recursion'

def _find_references(self, items, depth=0):

    reference_map = {}
    if ((not items) or (depth >= self.max_depth)):
        return reference_map
    if isinstance(items, dict):
        iterator = items.values()
    else:
        iterator = items
    depth += 1
    for item in iterator:
        if isinstance(item, (Document, EmbeddedDocument)):
            for (field_name, field) in item._fields.iteritems():
                v = item._data.get(field_name, None)
                if isinstance(v, DBRef):
                    reference_map.setdefault(field.document_type, set()).add(v.id)
                elif (isinstance(v, (dict, SON)) and ('_ref' in v)):
                    reference_map.setdefault(get_document(v['_cls']), set()).add(v['_ref'].id)
                elif (isinstance(v, (dict, list, tuple)) and (depth <= self.max_depth)):
                    field_cls = getattr(getattr(field, 'field', None), 'document_type', None)
                    references = self._find_references(v, depth)
                    for (key, refs) in references.iteritems():
                        if isinstance(field_cls, (Document, TopLevelDocumentMetaclass)):
                            key = field_cls
                        reference_map.setdefault(key, set()).update(refs)
        elif isinstance(item, DBRef):
            reference_map.setdefault(item.collection, set()).add(item.id)
        elif (isinstance(item, (dict, SON)) and ('_ref' in item)):
            reference_map.setdefault(get_document(item['_cls']), set()).add(item['_ref'].id)
        elif (isinstance(item, (dict, list, tuple)) and ((depth - 1) <= self.max_depth)):
            references = self._find_references(item, (depth - 1))
            for (key, refs) in references.iteritems():
                reference_map.setdefault(key, set()).update(refs)
    return reference_map
