Auto-Increment Sequence in MongoDB
MongoDB does not have the auto-increment out-of-the-box feature like SQL Database. By default, it uses a 12-byte ObjectId for the _id field as the Primary key to uniquely identify the Documents. However, there are situations when we want the _id field to have some values that automatically increase beyond ObjectId.
Since this is not the default feature in MongoDB, we will program this feature using a counters collection as suggested by MongoDB Documentation.
Use counter Collection
You follow the following product document. We want the _id field to be an ascending sequence of integers starting from 1, 2, 3, 4 to n.
{ "_id" : 1 , "product_name" : "Apple iPhone" , "category" : "mobiles" }
To do this, create a counters collection to track the final range value for all sequence fields.
> db . createCollection ( "counters" )
We will now insert the following Document in counters Collection with its productid key.
{ "_id" : "productid" , "sequence_value" : 0 }
Field sequence_value tracks the last value of that sequence.
Use the following code to insert this sequence document into counters collection:
> db . counters . insert ({ _id : "productid" , sequence_value : 0 })
Create JavaScript function
Now, we will create a getNextSequenceValue function, which accepts the array name as its input, increments the array value by 1 and returns the updated number. In this example, the array name is the productid .
> function getNextSequenceValue ( sequenceName ){ var sequenceDocument = db . counters . findAndModify ( { query :{ _id : sequenceName }, update : { $inc :{ sequence_value : 1 }}, new : true }); return sequenceDocument . sequence_value ; }
Use JavaScript function
Now we use the getNextSequenceValue function while creating a new Document and assigning the returned range value as the Document's _id field.
Insert two Document templates by using the following 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 you can see, we used the getNextSequenceValue function to set the value for the _id field.
To test this feature, we retrieve the Documents using the find command:
> db . prodcuts . find ()
The query returns documents with _id fields that are automatically incremented.
{ "_id" : 1 , "product_name" : "Apple iPhone" , "category" : "mobiles" } { "_id" : 2 , "product_name" : "Samsung S3" , "category" : "mobiles" }
According to Tutorialspoint
Last lesson: Working with Rockmongo
Next article: GridFS in MongoDB
You should read it
- Print pages in JavaScript
- Syntax of JavaScript
- JavaScript location in HTML File
- How to create a word counter in JavaScript
- What is JavaScript? Can the Internet exist without JavaScript?
- What is Currying in Javascript? How to use Currying in JavaScript
- Things to know about 'this' in JavaScript
- Udemy's top 5 JavaScript courses
May be interested
- GridFS in MongoDBgridfs is the mongodb specification for storing and collecting large files such as images, audio, video files, etc. it is a type of file system to store files but its data is stored inside mongodb collections. .
- Capped Collection in MongoDBcapped collections are fixed-sized circular collection that follow the insert order to enhance the performance of create, read, and delete operations.
- Overview of MongoDBmongodb is a cross-platform database, operating on the concepts of collection and document, it provides high performance, high availability and easy scalability.
- Advantages of MongoDBany relation database has a unique schema design to index the data tables and relationships between those tables. meanwhile in mongodb there is no concept of relationship.
- Install MongoDBinstructions for installing mongodb on windows.
- Data modeling in MongoDBdata in mongodb has a flexible schema. documents in the same collection need not have the same set of fields or structures, and common fields in collection documents can keep different data types.