## Considerations 

Generally in MongoDB, you would not use an auto-increment pattern for the _id field, or any field, because it does not scale for databases with large numbers of documents. Typically the default value ObjectId is more ideal for the _id . 

## Procedures 

## Use Counters Collection 

Counter Collection Implementation Use a separate counters collection to track the last number sequence used. The _id field contains the sequence name and the seq field contains the last value of the sequence. 

1. Insert into the counters collection, the initial value for the userid : 

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

2. Create a getNextSequence function that accepts a name of the sequence. The function uses the findAndModify() method to atomically increment the seq value 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 getNextSequence() function during insert() . 

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

You can verify the results with find() : 

db.users.find() 

The _id fields contain incrementing sequence values: 

