简体   繁体   中英

auto increment a field in mongodb

I need to find a way to auto-increment the "Bill_id" field by 1 , whenever I insert a new item to a nested array in a collection: this is the structure of the nested document I also found this demo on the official documentation : 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;
}

but I didn't know how to use the solution because it's proposing a JavaScript function that does all the work However I am working with python script , and to be specific a REST API using flask

Write a similar function mentioned in the docs, in python. This is what I use.

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

This will return the "user_id" of the last added document. Just increment it by one, and do a simple insert for the new document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM