Auto Increment in MongoDB
Overview
In a relational database, a feature is provided which allows increasing the value of a field automatically at every insertion by setting that field to the auto-increment. And in the NoSQL databases like MongoDB, allows the user to have more flexible data management, and auto-generated data is limited by the server. But we can achieve the auto-increment in MongoDB by using the counter collection on the field.
Prerequisites
It is assumed that the MongoDB cluster and Atlas account are already installed and configured. If not done as of now then follow the procedure given below:
- Create one new cluster or make ready any old one. MongoDB clusters can also be created for free.
- Now a database user is required to be created and after that insert your public IP address for taking network access to the cluster.
- Download the mongo shell in your system and the $PATH variable of your system add the <directory in which mongo shell is downloaded>/bin.
- The connection string of the cluster is required to be used for the cluster connection and for getting access by the Mongo shell.
How Does Auto Increment Work in MongoDB
Unlike relational databases, the auto-increment feature is not provided as a default feature by MongoDB, but the auto-increment in MongoDB can be achieved by counter-collection. There is a single document in the counter-collection by which the current unique identifier value is tracked to achieve MongoDB auto increment.
How to Use Counter Collection
Consider the following students document. We want that, the _id field to have an auto-incremented integer sequence feature enabled
We are creating a counter collection for this, which is used for tracking the value of the last sequence of each sequence field of the collection.
Now, a document with the studentId as the key is inserted in the counters collection
The last sequence value is tracked by the sequence_value. The code given below is used for sequence document insertion in the counters collection.
How to Create and Use JavaScript Function
Creating Javascript Function:
We can also achieve MongoDB auto increment by creating a javascript function. Create a function getNextSequenceValue that takes the name of the sequence as its input. Then, the sequence number is incremented by 1. And the updated sequence number will be returned. studentId is the sequence number in our case.
Using the Javascript Function:
When we create a new document, then we will implement getNextSequenceValue. document's _id field will be assigned the value of the returned sequence. Write the code given below to insert two sample documents:
As we can see, here the getNextSequenceValue function is used for the value of the _id field. Now we will fetch all the documents from the students collection to test the functionality, below is the command to fetch all documents.
The following documents are returned by the above query: Output:
Creating Collections
At least two collections are required for this approach. Details of the products are stored in the first collection, so we will create the first collection with the name products. For the creation of the products collection, run the command given below:
The current unique identifier value for the products will be stored in the second collection. And the name of the second collection will be counters. For the creation of counters collection, run the following given command.
Creating Triggers
Log in to your MongoDB Atlas account, to use triggers for MongoDB auto increment. Then, open the cluster in which you are desired to work. And then click on triggers.
Now click on the add trigger button. Set the value of the fields as per the values given below:
Set the cluster and database name according to your cluster and database name.
Write the code given below in the function field:
Then for saving the trigger, click on the save button.
Running Triggers
In the code given above, first of all, we are initializing the counters collection and creating a trigger for inserting events for the collection products. The trigger is executed when a document is inserted into the products collection by which the value of the seq_value field is updated in the counters collection. And the seq_value is added as the value of the productId field in the products collection. The field value is increased by the specified value by the MongoDB inc operator. The incremented number is automatically returned by the returnNewDocument parameter when it is set to true. While a new productId counter is added while the recent namespace does not have it if the upsert parameter value is set to true.
To test the working of the trigger, run the command given below for inserting data into the products collection.
Run the command given below to check the consistency.
The following result will get as output after the execution completion: Output:
Run the following command for testing the document in the counters collection
Output:
Now we can see that the value of the seq_field in the counters collection is increased from 0 to 3 as three documents are inserted by us in the products collection.
FAQs
Q. Does the auto-incrementing feature is supported by MongoDB as the default feature?
A. No, the auto-incrementing feature is not supported by MongoDB as the default feature.
Q. How auto increment can be achieved in MongoDB?
A. We can achieve an auto increment in MongoDB by counter collection. The counter collection helps us in keeping track of the value of unique sequence numbers.
Conclusion
- We can achieve the auto increment in MongoDB by using the counter collection on the field.
- Unlike relational databases, the auto-increment feature is not provided as a default feature by MongoDB, but the auto-increment in MongoDB can be achieved by counter-collection.