python - 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'
解决方案
您可以使用 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
推荐阅读
- reactjs - React Native 使用多个组件而不共享状态
- python - python中两个单词之间需要空格,有两个输入
- c# - log4net:关闭在层次结构 [MyRepository] 上调用
- node.js - MongoDB 指南针断开连接
- sql-server - 带排序的 SQL 实际执行计划成本高
- javascript - 如何在javascript中写入文本文件而不覆盖文本?
- c - 从二叉搜索树中删除具有 2 个子节点的节点
- javascript - 尝试从内部存储数据中使用 JSON.parse 时收到错误
- python - 从 python 中的 gnuradio src 对象确定样本的大小
- php - 如何保护我用于客户登录的 Api 而不会使其他人易受攻击