MongoDB Auto-Increment Sequence

Auto Increment Sequence in MongoDB is not a default feature. We  will automatically attain this by utilizing a counters collection as recommended by the MongoDB documentation.

Utilizing counter Collection

Consider the accompanying document. We need the _id field to be an auto-increment  number arrangement beginning from 1,2,3,4 upto n.

{"_id":1,"product_name": "Mobile Phone",
"class": "mobiles"
}

For this, make a counters collection which will stay informed regarding the last succession esteem for all the arrangement fields.

db.createCollection("counters")

Presently, we will embed the accompanying archive in the counters collection with productid as its key:

{"_id":"productid","sequence_value": 0
}

The field sequence_value stays informed regarding the last value of the arrangement.

Utilize the accompanying code to embed this arrangement archive in the counters collection :

db.counters.insert({_id:"productid",sequence_value:0})

Creating Javascript Function

Presently, we will take getNextSequenceValue  the grouping name as its input, increase the succession number by 1 and give back where it’s due arrangement number. For our situation, the sequence name is productid.

{query:{_id: sequencename },redesign: {$inc:{sequence_value:1}},
new:true
});
return sequencedocument.sequence_value;
}

Utilizing the Javascript Function

We will now utilize the function getnextsequencevalue while creating another record and appointing the returned succession esteem as report’s _id field.

Embed two example documents utilizing the accompanying code:

db.products.insert({"_id":getnextsequencevalue("productId"),"product_name":"apple iphone",
"category":"mobiles"})
>db.products.insert({
"_id":getnextsequencevalue("productId"),
"product_name":"samsung S3",
"category":"mobiles"})

As should be obvious, we have utilized the getnextsequencevalue function to set quality for the _id field.

To check the functionality, let us bring the documents utilizing find command:

db.prodcuts.find()

The above question gave back where its due documents having the auto-augmented _id field:

Each one article in MongoDB as of now has an id, and they are sort able in insertion request. What is not right with getting collection of client articles, emphasizing over it and utilize this as augmented ID.

MongoDB holds the _Id field in the top level of all documents as an essential key. _id must be novel, and dependably has a file with a one of a kind demand. Then again, aside from the exceptional requirement you can utilize any quality for the _Id field in your collections. This exercise depicts two techniques for making an augmenting arrangement number for the _id field utilizing the accompanying:

  • Utilization Counters Collection
  • Idealistic Loop

Contemplations

For the most part in MongoDB, you would not utilize an auto-addition design for the _id field, or any field, on the grounds that it doesn’t scale for databases with expansive quantities of documents. Normally the default esteem ObjectId is more perfect for the _id.

Using Counters Collection

Counter Collection Implementation

Utilize a different counters gathering to track the last number grouping utilized. The _id field contains the grouping name and the seq field contains the last estimation of the arrangement.

Embed into the counters accumulation, the introductory worth for the userid:

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

Make a getnextsequence work that acknowledges a name of the arrangement. The capacity utilizes the findandmodify() system to molecularly augment the seq esteem and return this new esteem:

capacity getnextsequence(name) {var ret = db.counters.findandmodify({
question: { _id: name },
overhaul: { $inc: { seq: 1 },
new: genuine
}
);
return ret.seq;
}

Utilize this getnextsequence() capacity amid addition().

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

You can confirm the results with find():

db.users.find()The _id fields contain increasing succession values:{
_id : 1,
name: "Sarah C."
}
{
_id : 2,
name : "Sway D."
}

findAndModify Behavior

At the point when findAndModify() incorporates the upsert: genuine alternative and the question field(s) is not remarkably listed, the system could embed a record different times in specific circumstances. For example, if numerous customers each one summon the system with the same inquiry condition and these routines finish the discover stage before any of strategies perform the alter stage, these systems could embed the same report.