Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MongoDB grows automatically


May 17, 2021 MongoDB


Table of contents


MongoDB grows automatically

MongoDB does not have the same auto-growth capabilities as SQL, and MongoDB's _id is the system's automatically generated 12-byte unique identity.

However, in some cases, we may need to implement ObjectId auto-growth.

Since MongoDB doesn't do this, we can do it programmatically, and we'll automatically grow the _id in the counters collection.


Use the counters collection

Consider the following products documentation. We _id the automatic growth from 1,2,3,4 to n in the field.

{
  "_id":1,
  "product_name": "Apple iPhone",
  "category": "mobiles"
}

To do this, create a set of counters, and the sequence field values can be automatically long:

>db.createCollection("counters")

Now let's insert the following document into the counters collection, using productid as key:

{
  "_id":"productid",
  "sequence_value": 0
}

sequence_value field is a value after the sequence grows automatically.

Insert the sequence document of the counters collection with the following command:

>db.counters.insert({_id:"productid",sequence_value:0})

Create a Javascript function

Now that we create the function getNextSequenceValue as input to the sequence name, the specified sequence automatically increases by 1 and returns the latest sequence value. In the instance of this article, the sequence is called 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 functions

Next we'll create a new document using the getNextSequenceValue function and set the _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 _id field.

To verify that the function is valid, we can read the document using the following command:

>db.prodcuts.find()

The above command returns the following results, and we _id that the field is self-growing:

{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}

{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }