def set_mongodb_entity(self, entity_id):
        sql = """
            SELECT
                REPLACE(REPLACE(e.entity_definition_keyname, '_', '-'), '.', '-') AS entity_definition,
                e.id         AS entity_id,
                e.sharing    AS entity_sharing,
                e.created    AS entity_created,
                IF(CAST(e.created_by AS UNSIGNED) > 0, CAST(e.created_by AS UNSIGNED), NULL) AS entity_created_by,
                e.changed    AS entity_changed,
                IF(CAST(e.changed_by AS UNSIGNED) > 0, CAST(e.changed_by AS UNSIGNED), NULL) AS entity_changed_by,
                e.deleted    AS entity_deleted,
                IF(CAST(e.deleted_by AS UNSIGNED) > 0, CAST(e.deleted_by AS UNSIGNED), NULL) AS entity_deleted_by,
                e.is_deleted AS entity_is_deleted,
                e.old_id     AS entity_old_id
            FROM
                entity AS e
            WHERE e.id = %s
            LIMIT 1;
        """

        r = self.db_get(sql, entity_id)

        mysql_id = r.get('entity_id')

        e = {}
        e['_mid'] = mysql_id
        e['_definition'] = r.get('entity_definition')
        e['_sharing'] = r.get('entity_sharing')

        if r.get('entity_created'):
            e.setdefault('_created', {})['at'] = r.get('entity_created')
        if r.get('entity_created_by'):
            e.setdefault('_created', {})['by'] = r.get('entity_created_by')
        if e.get('_created'):
            e['_created']['type'] = 'action'
            e['_created'] = [e.get('_created')]

        if r.get('entity_changed'):
            e.setdefault('_changed', {})['at'] = r.get('entity_changed')
        if r.get('entity_changed_by'):
            e.setdefault('_changed', {})['by'] = r.get('entity_changed_by')
        if e.get('_changed'):
            e['_changed']['type'] = 'action'
            e['_changed'] = [e.get('_changed')]

        if r.get('entity_is_deleted') and r.get('entity_deleted'):
            e.setdefault('_deleted', {})['at'] = r.get('entity_deleted')
        if r.get('entity_is_deleted') and r.get('entity_deleted_by'):
            e.setdefault('_deleted', {})['by'] = r.get('entity_deleted_by')
        if e.get('_deleted'):
            e['_deleted']['type'] = 'action'
            e['_deleted'] = [e.get('_deleted')]

        viewers = self.__get_mongodb_right(mysql_id, ['viewer', 'expander', 'editor', 'owner'])
        if viewers:
            e['_viewer'] = [{'reference': x, 'type': 'reference'} for x in list(set(viewers))]

        expanders = self.__get_mongodb_right(mysql_id, ['expander', 'editor', 'owner'])
        if expanders:
            e['_expander'] = [{'reference': x, 'type': 'reference'} for x in list(set(expanders))]

        editors = self.__get_mongodb_right(mysql_id, ['editor', 'owner'])
        if editors:
            e['_editor'] = [{'reference': x, 'type': 'reference'} for x in list(set(editors))]

        owners = self.__get_mongodb_right(mysql_id, ['owner'])
        if owners:
            e['_owner'] = [{'reference': x, 'type': 'reference'} for x in list(set(owners))]

        parent = self.__get_mongodb_parent(entity_id=mysql_id, recursive=False)
        if parent:
            e['_parent'] = [{'reference': x, 'type': 'reference'} for x in list(set(parent))]

        ancestor = self.__get_mongodb_parent(entity_id=mysql_id, recursive=True)
        if ancestor:
            e['_ancestor'] = [{'reference': x, 'type': 'reference'} for x in list(set(ancestor))]

        sql = """
            SELECT
                p.id                    AS property_id,
                REPLACE(REPLACE(pd.dataproperty, '-', '_'), '.', '_')  AS property_dataproperty,
                pd.datatype             AS property_datatype,
                pd.formula              AS property_formula,
                pd.search               AS property_search,
                IF(pd.multilingual = 1, IF(p.language = 'english', 'en', 'et'), NULL) AS property_language,
                TRIM(p.value_formula)   AS value_formula,
                TRIM(p.value_string)    AS value_string,
                TRIM(p.value_text)      AS value_text,
                TRIM(p.value_display)   AS value_display,
                p.value_integer,
                p.value_decimal,
                p.value_boolean,
                p.value_datetime,
                p.value_reference,
                p.value_file,
                IF(pd.datatype = 'file', (SELECT s3_key FROM file WHERE id = p.value_file AND deleted IS NULL LIMIT 1), NULL) AS value_file_s3,
                IF(pd.datatype = 'file', (SELECT md5 FROM file WHERE id = p.value_file AND deleted IS NULL LIMIT 1), NULL) AS value_file_md5,
                IF(pd.datatype = 'file', (SELECT filename FROM file WHERE id = p.value_file AND deleted IS NULL LIMIT 1), NULL) AS value_file_name,
                IF(pd.datatype = 'file', (SELECT filesize FROM file WHERE id = p.value_file AND deleted IS NULL LIMIT 1), NULL) AS value_file_size,
                IF(pd.datatype = 'file', (SELECT url FROM file WHERE id = p.value_file AND deleted IS NULL LIMIT 1), NULL) AS value_file_url,
                p.value_counter,
                p.created,
                IF(CAST(p.created_by AS UNSIGNED) > 0, CAST(p.created_by AS UNSIGNED), NULL) AS created_by,
                p.is_deleted,
                p.deleted,
                IF(CAST(p.deleted_by AS UNSIGNED) > 0, CAST(p.deleted_by AS UNSIGNED), NULL) AS deleted_by
            FROM
                property AS p,
                property_definition AS pd
            WHERE pd.keyname = p.property_definition_keyname
            AND p.entity_id = %s
            AND p.is_deleted = 0
            AND pd.dataproperty NOT IN ('entu-changed-by', 'entu-changed-at', 'entu-created-by', 'entu-created-at')
            AND pd.dataproperty NOT LIKE 'auth_%%'
            AND pd.datatype NOT IN ('counter')
            AND pd.formula = 0;
        """

        properties = {}
        for r2 in self.db_query(sql, mysql_id):
            value = {}

            if r2.get('property_datatype') == 'string' and r2.get('value_string'):
                value['value'] = r2.get('value_string')
            elif r2.get('property_datatype') == 'text' and r2.get('value_text'):
                value['value'] = r2.get('value_text')
            elif r2.get('property_datatype') == 'integer' and r2.get('value_integer') != None:
                value['value'] = r2.get('value_integer')
            elif r2.get('property_datatype') == 'decimal' and r2.get('value_decimal') != None:
                value['value'] = float(r2.get('value_decimal'))
            elif r2.get('property_datatype') == 'boolean' and r2.get('value_boolean') != None:
                value['value'] = bool(r2.get('value_boolean'))
            elif r2.get('property_datatype') in ['date', 'datetime'] and r2.get('value_datetime') != None:
                value['value'] = r2.get('value_datetime')
            elif r2.get('property_datatype') == 'reference' and r2.get('value_reference'):
                value['reference'] = r2.get('value_reference')
            elif r2.get('property_datatype') == 'counter-value' and r2.get('value_string'):
                value['value'] = r2.get('value_string')
            elif r2.get('property_datatype') == 'file' and r2.get('value_file'):
                value['value'] = r2.get('value_file_name')
                if r2.get('value_file_url'):
                    value['url'] = r2.get('file')
                else:
                    value['size'] = r2.get('value_file_size')
                    if r2.get('value_file_md5', None):
                        value['md5'] = r2.get('value_file_md5')
                    if r2.get('value_file_s3', None):
                        value['s3'] = r2.get('value_file_s3')

            if not value:
                continue

            value['_mid'] = r2.get('property_id')
            value['type'] = r2.get('property_datatype')

            if r2.get('property_language'):
                value['language'] = r2.get('property_language')

            # if r2.get('created'):
            #     value.setdefault('created', {})['at'] = r2.get('created')
            # if r2.get('created_by'):
            #     value.setdefault('created', {})['by'] = r2.get('created_by')
            #
            # if r2.get('is_deleted') and r2.get('deleted'):
            #     value.setdefault('deleted', {})['at'] = r2.get('deleted')
            # if r2.get('is_deleted') and r2.get('deleted_by'):
            #     value.setdefault('deleted', {})['by'] = r2.get('deleted_by')

            e.setdefault(r2.get('property_dataproperty'), []).append(value)

            # if r2.get('value_display') and r2.get('property_search') == 1:
            #     if r2.get('property_language'):
            #         e.setdefault('_search', {}).setdefault(r2.get('property_language'), []).append(r2.get('value_display').lower())
            #     else:
            #         e.setdefault('_search', {}).setdefault('et', []).append(r2.get('value_display').lower())
            #         e.setdefault('_search', {}).setdefault('en', []).append(r2.get('value_display').lower())

        # for l in ['et', 'en']:
        #     if l in e.get('_search', {}):
        #         e['_search'][l] = list(set(e['_search'][l]))

        #Create or replace Mongo object
        try:
            mongo_entity_version = self.mongodb().entityVersion.find_one({'_mid': mysql_id}, {'_id': False, '_entity': True})
            if mongo_entity_version:
                e['_entity'] = mongo_entity_version.get('_entity')
            else:
                e['_entity'] = self.mongodb().entity.insert_one({}).inserted_id
            self.mongodb().entityVersion.insert_one(e)
        except Exception, err:
            self.captureException()
            logging.error('MongoDb error: %s - %s' % (err, e))
dataset/ETHPy150Open argoroots/Entu/app/main/db.py/Entity.set_mongodb_entity/original