每当我将新项目插入集合中的嵌套数组时,我都需要找到一种将“Bill_id”字段自动递增 1 的方法: this is the structure of the nested document 我还在官方文档中找到了这个演示: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
但我不知道如何使用该解决方案,因为它提出了一个可以完成所有工作的 JavaScript 函数 但是我正在使用 python 脚本,具体来说是使用 flask 的 REST API
最佳答案
在 python 中编写文档中提到的类似函数。这是我用的。
def getLastUserId(self):
if len(list(self.find())) is not 0:
last_user = list(self.find({}).sort("user_id", -1).limit(1))
return last_user[0]["user_id"]
else:
return 0
这将返回最后添加的文档的“user_id”。只需将它加一,然后为新文档做一个简单的插入。
关于javascript - 自动增加mongodb中的一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49494667/