MongoDB Learning Note One ID self-growing

Source: Internet
Author: User
Tags mongodb


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


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:?
1 2 3) 4 5
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.