'Converts a record from version 0 (no "schema_version" key
in the document) to version 1 (`doc["schema_version"] ==
1`). Version 1 adds an "openports" nested document to ease
open ports based researches.'

def migrate_schema_hosts_0_1(self, doc):

    assert ('schema_version' not in doc)
    assert ('openports' not in doc)
    update = {'$set': {'schema_version': 1}}
    updated_ports = False
    openports = {}
    for port in doc.get('ports', []):
        if (port.get('state_state') == 'open'):
            openports.setdefault(port['protocol'], {}).setdefault('ports', []).append(port['port'])
        if (('screenshot' in port) and ('screenwords' not in port)):
            screenwords = utils.screenwords(self.getscreenshot(port))
            if (screenwords is not None):
                port['screenwords'] = screenwords
                updated_ports = True
    for proto in list(openports):
        count = len(openports[proto]['ports'])
        openports[proto]['count'] = count
        openports['count'] = (openports.get('count', 0) + count)
    if (not openports):
        openports['count'] = 0
    if updated_ports:
        update['$set']['ports'] = doc['ports']
    update['$set']['openports'] = openports
    return update
