Reputation: 39
I have collections in MongoDB. I need to get values from collection. If values - none -> take values from other collection and set (id +=1) and save. My code:
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
when i debug this code -> error
TypeError: unsupported operand type(s) for +=: 'dict' and 'int'
Upvotes: 0
Views: 47
Reputation: 3423
You can use mongoDb $inc operator to increment a field:
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
Upvotes: 1