Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef.

def _parse_canonical_dbpointer(doc):
    """Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef."""
    dbref = doc['$dbPointer']
    if len(doc) != 1:
        raise TypeError('Bad $dbPointer, extra field(s): %s' % (doc,))
    if isinstance(dbref, DBRef):
        dbref_doc = dbref.as_doc()
        # DBPointer must not contain $db in its value.
        if dbref.database is not None:
            raise TypeError(
                'Bad $dbPointer, extra field $db: %s' % (dbref_doc,))
        if not isinstance(dbref.id, ObjectId):
            raise TypeError(
                'Bad $dbPointer, $id must be an ObjectId: %s' % (dbref_doc,))
        if len(dbref_doc) != 2:
            raise TypeError(
                'Bad $dbPointer, extra field(s) in DBRef: %s' % (dbref_doc,))
        return dbref
    else:
        raise TypeError('Bad $dbPointer, expected a DBRef: %s' % (doc,))