【发布时间】:2022-01-06 21:55:32
【问题描述】:
我正在尝试在我的 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 部分有问题
【问题讨论】: