在MongoDB中自动增加字段值

4
我需要找到一种方法来使"Bill_id"字段自动加1,每当我在集合中的嵌套数组中插入一个新条目时: 这是嵌套文档的结构 我还在官方文档上找到了这个演示: 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。

1个回答

2

在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”。只需将其增加一,然后为新文档执行简单的插入即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接