EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Data Science Data Science Tutorials MongoDB Tutorial MongoDB Auto Increment
 

MongoDB Auto Increment

Priya Pedamkar
Article byPriya Pedamkar

Updated February 27, 2023

MongoDB Auto Increment

 

 

Introduction to MongoDB Auto Increment

MongoDB Auto Increment does not have the functionality which was available in SQL databases like MySQL, MSSQL, and ORACLE. Normally MongoDB uses by default 12 bytes object id for the _id field as the primary key to uniquely identify the collection documents in MongoDB. There is a scenario for the use of _id field to have some auto-increment value other than object _id in MongoDB. MongoDB auto-increment does not default the MongoDB feature; we will achieve the same using programmatically, and by using the counter collection.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax

Below is the syntax of auto-increment:

1. Create a function to generate auto-increment sequence:

function getValueForNextSequence(auto_increment_sequence_name){
var sequenceDoc = db.collection_name. FindAndModify ({
query:{_id: auto_increment_sequence_name },
update: {$inc:{sequence_value:1}},
new: true });
return sequenceDoc.sequence_value; }

2. Use the auto-increment sequence:

db.collection_name.insert (“field_name”: getValueForNextSequence (“field_name”), “field_name”: value_of_field)

Parameters

Below is the parameter description syntax of auto-increment:

  • Collection name: Collection name is defined as the collection name which we have used to insert data using the auto-increment sequence in MongoDB. We need to define the collection name while using the auto-increment sequence.
  • Function name: Function name define as for using auto-increment sequence we need to define it first. The function name is significant while inserting documents into the collection while using the sequence.
  • Find and modify: Find and modify is a method that we have used while inserting a document into the collection by using the find and modify method.
  • Field name: We have to define field names while inserting a document into the field. The field name is an important parameter while using the auto-increment sequence.
  • Query: Query is defined as which we have used in the auto-increment sequence.
  • Update: It is defined as an updated document from the collection by using the auto-increment sequence.

How does Auto Increment work in MongoDB?

Below is the working of auto-increment. We have generated auto-increment by creating an auto-increment sequence in MongoDB. The database sequence is defined as a database product that created unique values by getting an auto-increment. Autoincrement sequence is significant as transaction id was associated with a sequence in MongoDB. We have used the auto-increment sequence for multithreaded application, for the multithreaded application, we have to use the auto-increment sequence.

Normally MongoDB uses by default 12 bytes object id for the _id field as the primary key to uniquely identify the collection documents in MongoDB. There is a scenario for the use of _id field to have some auto-increment value other than object _id in MongoDB. MongoDB auto-increment does not have the functionality which was available in SQL databases like MySQL, MSSQL, and ORACLE.

Autoincrement is very useful and important. MongoDB auto-increment does not default feature of MongoDB; we will achieve the same using programmatically, and by using the counter collection. These seven steps are used to generate auto-increment function or sequence in MongoDB are as follows. There are seven steps that are used to generate auto-increment function or sequence in MongoDB. For generating auto-increment function, we need to generate the first collection on which we have created a sequence of auto-increment in MongoDB. The second step is to insert a document into the collection. We have checked the document after inserting a value into the collection.

The third step is to insert records into the collection. We have checked the document after inserting the record into the collection. The fourth step is to create a database sequence. The database sequence is used in auto-increment value. This is used in the auto-increment sequence. The fifth step is used to create a javascript function to create sequences in MongoDB. We have defined a function in javascript and calling at the time of inserting a record. In the sixth step, we have to define a function in javascript and calling when inserting a record in MongoDB. The seventh step is used to see the created sequence is properly used or not. We have to check in the last step that created an auto-increment sequence in properly working.

Examples to Implement MongoDB Auto Increment

Below are the examples mentioned:

Example #1

Create a collection to use auto-increment sequence

In below example we have created a collection name as “collection_seq” to generate auto Increment value:

Code:

db.createCollection("collection_seq")

Output:

MongoDB Auto Increment1

Example #2

Insert a document into the collection

We have inserted the below document into the collection to check the auto-increment sequence:

Code:

({"_id" : "col_id", "seq_val": 0})

Example #3

Insert the record into collection

We have inserted the record into the collection to check the auto-increment sequence. Below is the example of inserting the record into the collection:

Code:

db.collection_seq.insert ({"_id" : "col_id", "seq_val": 0})

Output:

MongoDB Auto Increment2

Example #4

Create a javascript function

Below is the example of creating a javascript function are as follows. We have created function name as getSequenceNextValue:

Code:

function getSequenceNextValue(coll_seqName) {
var seq_col = db.collection_seq.findAndModify({
query: { _id: col_id },
update: { $inc: { seq_val: 1 } },
new: true
});
return seq_col.sequence_value;
}

Output:

get Sequence Next Value

Example #5

Use a javascript function

Below example shows that we have used above created javascript function in collection name as collection_seq:

Insert the first record:

Code:

db.collection_seq.insert({
"_id": getValueForNextSequence("col_id"),
"name": "ABC",
"spec": "book",
"category": "functional",
"plan": "regular"
})

Output:

MongoDB Auto Increment4

Insert the second record:

Code:

db.collection_seq.insert({
"_id": getValueForNextSequence("col_id"),
"name": "PQR",
"spec": "book1",
"category": "funct

Output:

second record

Example #6

Use a javascript function

Below example shows use javascript function:

Code:

db.collection_seq.find()

Output:

javascript function

Recommended Articles

This is a guide to MongoDB Auto Increment. Here we discuss an introduction, syntax, how it works, and the respective examples. You can also go through our other related articles to learn more –

  1. MongoDB Administration
  2. MongoDB Collection
  3. order by in MongoDB
  4. Lookup in MongoDB

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - ENROLL NOW