javascript - 自动增加mongodb中的一个字段

标签 javascript python mongodb

每当我将新项目插入集合中的嵌套数组时,我都需要找到一种将“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/

相关文章:

javascript - 如何防止电子邮件地址的 css 自动断字

javascript - 使用 d3.js 的组元素 (<g>) 的渲染顺序

javascript - Vue + Nuxt.js - 如何使用组件缓存整个页面?

Python 回复 : Overwrite Issue

python - 使用 numpy 将矩阵 int 值映射到 str 的有效方法

javascript - $lookup 深度嵌套对象

javascript - 如何扩展nodejs模块

python - Boto 在 ec2 实例上执行 shell 命令

python - 使用 networkx (python) 读取没有节点标签的 GML 文件

php - Symfony2 的 mongoDB 返回一个 loggablecursor 而不是我的实体