MongoDB Learning Note One ID self-growing

Source: Internet
Author: User

The following is the original website address:

http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

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:

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:
function Getnextsequence (name) {   var ret = db.counters.findAndModify (          {            query: {_id:name},            update: {$ Inc: {seq:1}},            new:true          }   );   return ret.seq;}
3. Use the Getnextsequence function when inserting data in the next step:
Db.users.insert (   {     _id:getnextsequence ("userid"),///Note the Getnextsequence parameter is consistent with the _ID value in the Counter collection     name: "Sarah C."   }) Db.users.insert (   {     _id:getnextsequence ("userid"),     name: "Bob D."   })
4. You can try to see the results:
Db.users.find ()
5. The _id field contains the values for the autogrow sequence:
{  _id:1,  name: "Sarah C."} {  _id:2,  name: "Bob D."}
Findandmodify This method contains updates, the query field is not necessarily a unique index, and the method can insert the same document multiple times in some cases. For example, when multiple clients are using the same query criteria,

Call this method, calling these methods must complete the query operation before performing the update operation, and these methods can insert the same document.

In a counter case, the query field is the _id field, and it always has a separate index. Let's look at the following example:

function Getnextsequence (name) {   var ret = db.counters.findAndModify (          {            query: {_id:name},            update: {$ Inc: {seq:1}},            new:true,            upsert:true          }   );   return ret.seq;}
If multiple clients call the Getnextsequence () method with the same parameters, then we find that one of the following behaviors will occur:

A findandmodify () method will successfully insert a document;

0 or more findandmodify () methods will update the newly inserted file;

0 or more findandmodify () methods when they attempt to insert duplicate data;

If the method fails due to a unique constraint violation, try again.

Optimistic Loop

Slightly.

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: info-contact@alibabacloud.com 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.