首页 > 解决方案 > MongoDB将增量添加到id

问题描述

我在 MongoDB 中有集合。我需要从收藏中获取价值。如果 values - none -> 从其他集合中获取值并设置 (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'

标签: pythonmongodb

解决方案


您可以使用 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

推荐阅读