MongoDB将增量添加到ID

时间:2018-10-19 06:49:23

标签: python mongodb

我在MongoDB中有集合。我需要从集合中获取价值。如果值-无->从其他集合中获取值并设置(id + = 1)并保存。 我的代码:

def get_next_sequence(self):
    client = MongoClient(self.__connection_string)
    db = client[self.__db_name]
    collection = db['counters']
    get_id = collection.find_one({'_id': 'breaks_column_id'})
    if get_id is None:
        db['counters'].insert_one({'_id': 'breaks_column_id', 'seq': 1})
        return 1
    else:
        get_id += 1
        db['counters'].update_one({'_id': 'breaks_column_id', 'seq': get_id})
        return get_id

当我调试此代码时->错误

TypeError: unsupported operand type(s) for +=: 'dict' and 'int'

1 个答案:

答案 0 :(得分:1)

您可以使用mongoDb $ inc运算符来增加字段:

    def get_next_sequence(self):
        client = MongoClient(self.__connection_string)
        db = client[self.__db_name]
        collection = db['counters']
        result = collection.find_one({'_id': 'breaks_column_id'})
        print(result)
        if result is None:
            db['counters'].insert_one({'_id': 'breaks_column_id', 'seq': 1})
            return 1
        else:
            db['counters'].update_one({'_id': 'breaks_column_id'}, {'$inc' : {'seq' : 1}})
            # if run in paralel this won't return necessarely an accurate result
            return result['seq'] + 1
相关问题