MongoDB auto-grow
MongoDB does not have the automatic growth function like SQL. MongoDB's _id is a 12-byte unique identifier automatically generated by the system.
But in some cases, we may need to implement the ObjectId automatic growth function.
Since MongoDB does not implement this function, we can implement it programmatically. Below we will Implement automatic growth of the _id field in the counters collection.
Using the counters collection
Consider the following products document. We want the _id field to implement Auto-increment function from 1,2,3,4 to n.
{ "_id":1, "product_name": "Apple iPhone", "category": "mobiles" }
To this end, create a counters collection, and the sequence field value can be automatically long:
>db.createCollection("counters")
Now we insert the following document into the counters collection, using productid as the key:
{ "_id":"productid", "sequence_value": 0 }## The #sequence_value field is a value after the sequence has been automatically increased. Use the following command to insert into the sequence document of the counters collection:
>db.counters.insert({_id:"productid",sequence_value:0})
Create Javascript function Now, we create the function getNextSequenceValue as the input of the sequence name, The specified sequence is automatically incremented by 1 and the latest sequence value is returned. In the example of this article the sequence is named productid .
>function getNextSequenceValue(sequenceName){ var sequenceDocument = db.counters.findAndModify( { query:{_id: sequenceName }, update: {$inc:{sequence_value:1}}, new:true }); return sequenceDocument.sequence_value; }
Using Javascript functionNext we will use the getNextSequenceValue function to create a new document, And set the document _id automatically to the returned sequence value:
>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 use the getNextSequenceValue function to set the _id field. In order to verify whether the function is valid, we can use the following command to read the document:
>db.products.find()The above command will return the following results, and we find that the _id field is auto-increasing:
{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"} { "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }