MongoDB does not have auto-growth functions like SQL, and MongoDB's _id is a 12-byte unique identifier that is automatically generated by the system.
In some cases, however, we may need to implement the OBJECTID auto-grow feature.
Since MongoDB does not implement this function, we can do it programmatically, the following we will implement the _id field automatically grow in the Counters collection.
Using the Counters Collection
Consider the following products documentation. We want the _id field to implement the auto-grow function from 1,2,3,4 to N.
{ "_id": 1, "product_name": "Apple iPhone", "category": "Mobiles"}
To do this, create a counters collection where the sequence field values 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 is automatically grown.
Use the following command to insert the counters collection in the sequence document:
>db.counters.insert ({_id: "ProductID", sequence_value:0})
Creating Javascript Functions
Now, we create the function Getnextsequencevalue as input to the sequence name, and the specified sequence automatically grows by 1 and returns the latest sequence value. In the example in 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 functions
Next we will use the Getnextsequencevalue function to create a new document and set the document _ID automatically for 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.
To verify that the function is valid, we can read the document using the following command:
>db.prodcuts.find ()
The above command will return the following results, and we find that the _id field is self-growing:
{"_id": 1, "product_name": "Apple iPhone", "category": "Mobiles"} {"_id": 2, "product_name": "Samsung S3", "category": "Mobiles"}
MongoDB Auto Grow