Overview
The _id field of MongoDB exists as a primary key at the top level of all documents, and _id must be unique and always have a unique constraint index. In addition to the unique constraint, you can use any value on the _id field in the collection,
The following guide describes two ways to create a self-increment sequence on _id:
Use Counter Collection
Optimistic Loop
Precautions
In general, you will not be willing to use the _id field, or any field on the self-increment mode, because there will not be a large number of documents to form a large-scale database, usually more ideal is the default _id.
implementation Process
Use Counter Collection
Counter Collection implementations:
Use a separate counter set to track the last sequence of numbers we use. The _id field contains the sequence name and the last value of the sequence in the sequence field.
1. Insert the Counter collection and set the initial value to UserID:?
1 2 3 4 5 6 |
Db.counters. Insert ({_id: "userid", seq:0}) |
2, create a getnextsequence function, the parameter is the name of the sequence, the function uses the Findandmodify () method to automatically increase the value of the sequence and return the result after growth:?