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

4.6 ★ | 9 Vote

May be interested

  • Text Search in MongoDBText Search in MongoDB
    starting with version 2.4, mongodb started supporting text indexes to search within the string content.
  • Shard in MongoDBShard in MongoDB
    sharding is a process of storing data records across multiple devices and it is a method of mongodb to meet the requirement for increasing data. when the size of the data increases, a single device cannot be enough to store data.
  • Learn about Java Driver in MongoDBLearn about Java Driver in MongoDB
    in the following article, we will introduce you some basic features of mongodv java driver as well as how to deploy and apply in practice.
  • Install MongoDBInstall MongoDB
    instructions for installing mongodb on windows.
  • SEQUENCE in SQLSEQUENCE in SQL
    sequence is often used because meeting the requirements of many applications is to require each row in a table to contain a unique value similar to the primary key.
  • Map Reduce in MongoDBMap Reduce in MongoDB
    in mongodb documentation, map-reduce is a data processing system that condenses a large amount of data into useful overall results. mongodb uses mapreduce command for map-reduce operation. in general, map reduce is used to handle large data sets.
  • Aggregation in MongoDBAggregation in MongoDB
    aggregation can be understood as aggregation. the aggregation operation handles data records and returns calculated results. the operations group the values ​​from multiple documents together, and can perform multiple operations on the grouped data to return a single result. in sql, count (*) and group by are equivalent to aggregation in mongodb.
  • Data modeling in MongoDBData modeling in MongoDB
    data 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.
  • How to use Aggregation Pipeline in MongoDBHow to use Aggregation Pipeline in MongoDB
    if you are using mongodb's mapreduce, it is best to switch to aggregation pipeline for more efficient computation.
  • GridFS in MongoDBGridFS in MongoDB
    gridfs 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. .