import pymongo
# 数据库
db = pymongo.MongoClient('mongodb://localhost:27017/')['abc']
# 计数器
counter = db['counter']
# book文档集合
books = db['books']
# 初始化计数器
def init_counter(sequence_name):
count_doc = {
'_id': sequence_name,
'sequence_value': 0
}
counter.insert_one(count_doc)
# 获取计数器自增值
def get_next_sequence_value(sequence_name):
updated_count_doc = counter.find_one_and_update({'_id': sequence_name},
{'$inc': {'sequence_value': 1}}, return_document=True)
return updated_count_doc['sequence_value']
if __name__ == '__main__':
init_counter('book_id')
init_counter在这里作为book的计数器,只需初始化执行一次就可以,sequence_name为id名称,如:book_id,
若是想作为其他文档集合计数器,直接改参数(即将'book_id'