自动递增pymongo

Auto increment pymongo

我正在尝试自动递增我的 mongo 集合中的一个字段。该字段是一个 'id' 字段,它包含每个文档的 'id'。例如。 1、2、3 等等

我想要发生的是插入一个新文档并从最后一个文档中取出 'id' 并向其添加 1,以便新文档是 lastID + 1。

我编写代码的方式使得它获取最后一个文档并将最后一个文档加 1,然后更新它。因此,如果最后一个 id 是 5,那么新文档将有 5,而我递增的文档现在有新的 'id' 6.

我不确定如何解决这个问题,因此我们将不胜感激。

代码

last_id = pokemons.find_one({}, sort=[( 'id', -1)])

last_pokemon = pokemons.find_one_and_update({'id' : last_id['id']}, {'$inc': {'id': 1}}, sort=[( 'id', -1)]) 

new_pokemon = {
              "name" : name, "avg_spawns" : avg_spawns, "candy" : candy, "img" : img_link, "weaknesses" : [], "type" : [], "candy_count" : candy_count, 
              "egg" : egg, "height" : height, "multipliers" : [], "next_evolution" : [], "prev_evolution" : [],
              "spawn_chance" : spawn_chance, "spawn_time" : spawn_time, "weight" : weight, "id" : last_pokemon['id'], "num" : last_pokemon['id'],
}

pokemons.insert_one(new_pokemon)
                 

new_pokemon 中的变量无关紧要,因为我只是遇到了 last_pokemon 部分的问题

MongoDB 命令中的 find_one 命令不支持排序功能。您必须使用限制参数设置为 1.

的普通查找命令
last_id = pokemons.find({}, {"id": 1}, sort=[('id', -1)]).limit(1).next()  # Will error if there are no documents in collection due to the usage of `next()`

last_id["id"] += 1

new_pokemon = {
              "name" : name, "avg_spawns" : avg_spawns, "candy" : candy, "img" : img_link, "weaknesses" : [], "type" : [], "candy_count" : candy_count, 
              "egg" : egg, "height" : height, "multipliers" : [], "next_evolution" : [], "prev_evolution" : [],
              "spawn_chance" : spawn_chance, "spawn_time" : spawn_time, "weight" : weight, "id" : last_id['id'], "num" : last_id['id'],
}

pokemons.insert_one(new_pokemon)