MongoDB does not have the same automatic growth function as SQL, and MongoDB’s_ id is the 12-byte unique ID automatically generated by the system.
But in some cases, we may need to implement the ObjectId auto-growth feature.
Since MongoDB does not implement this function, we can do it programmatically. Now we will automatically grow the_ id field in the counters collection. Consider the following products documents. We want the_ id field to grow automatically from 1, 2, 3, 4 to n. To do this, create a counters collection, and the sequence field values can be automatically long: Now let’s insert the following documents into the counters collection, using productid as the key: Use the following command to insert Now, we create the function getNextSequenceValue as the 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. Next we will use the As you can see, we use To verify that the function is valid, we can read the document using the following command: The above command returns the following result, and we find that the_ id field is self-growing: 3.45.1. Use counters collections ¶
{
"_id":1,
"product_name": "Apple iPhone",
"category": "mobiles"
}
>db.createCollection("counters")
{
"_id":"productid",
"sequence_value": 0
}
sequence_value
A field is a value after the sequence is automatically incremented.
counters
In the sequence document of the collection:>db.counters.insert({_id:"productid",sequence_value:0})
3.45.2. Create a Javascript function ¶
>function getNextSequenceValue(sequenceName){
var sequenceDocument = db.counters.findAndModify(
{
query:{_id: sequenceName },
update: {$inc:{sequence_value:1}},
"new":true
});
return sequenceDocument.sequence_value;
}
3.45.3. Use the Javascript function ¶
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"})
getNextSequenceValue
Function to set the_ id field.>db.products.find()
{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}
{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }