Latest web development tutorials

MongoDB automatically increase

MongoDB there is not the same as SQL capabilities for growing automatically, MongoDB's _id is 12 bytes that uniquely identifies the system automatically generated.

However, in some cases, we may need to implement ObjectId automatic growth feature.

Because MongoDB does not implement this feature, we can be programmed to achieve, we will achieve the following _id field grow automatically counters collection.


Use counters collection

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

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

To do this, create a set of counters, automatic sequence field values ​​can be long:

>db.createCollection("counters")

Now we insert the following documents to the counters in the collection, use productid as key:

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

sequence_value field is a sequence of values ​​by automatic growth after.

Use the following command sequence to insert the document counters of the collection:

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

Creating Javascript function

Now, we create getNextSequenceValue function as an input sequence name, the specified sequence will automatically grow by 1 and returns the latest sequence value. In the example in this article series 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 the Javascript function

Next we will use getNextSequenceValue function to create a new document and set the document _id automatic sequence value returned is:

>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 getNextSequenceValue function to set the _id field.

In order to verify the effectiveness of the function, we can use the following command to read the document:

>db.products.find()

The above command will return the following results, we found _id field is self-growth:

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

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