Is there a way to auto-increment the id in Mongo?

Asked

Viewed 1,240 times

2

You can do this, every time I create a new user for example it auto increments _id. Starting from 1 and going up to the number of users

  • https://docs.mongodb.com/v2.8/tutorial/create-an-auto-incrementing-field/

2 answers

4


Yes, following the example of documentation(create-an-auto-incrementing-field), it would be something like that:

1 - Enter the starting value for the field in the meter collection:

db.counters.insert(
   {
      _id: "userid",
      seq: 0
   }
)

2 - Create a function getNextSequence which accepts a sequence name. The function uses the method findAndModify() to atomically increment the value seq and return this new value:

function getNextSequence(name) {
   var ret = db.counters.findAndModify(
          {
            query: { _id: name },
            update: { $inc: { seq: 1 } },
            new: true
          }
   );
return ret.seq;
}

3 - Use this function getNextSequence() during insertion.

db.users.insert(
   {
     _id: getNextSequence("userid"),
     name: "Sarah C."
   }
)

db.users.insert(
   {
     _id: getNextSequence("userid"),
     name: "Bob D."
   }
)

More information see the documentation.

1

Mongodb’s own documentation has an example and shows you how to do it. Even they say that the method used is more recommended for the _id, just what you need. Give a look HERE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.