Concept of Capped Collections and Auto-Increment Sequence in MongoDB

Last updated on May 30 2022
Satyen Sahu

Table of Contents

Concept of Capped Collections and Auto-Increment Sequence in MongoDB

MongoDB – Capped Collections

Capped collections are fixed-size circular collections that follow the insertion order to support high performance for create, read, and delete operations. By circular, it means that when the fixed size allocated to the collection is exhausted, it will start deleting the oldest document in the collection without providing any explicit commands.
Capped collections restrict updates to the documents if the update results in increased document size. Since capped collections store documents in the order of the disk storage, it ensures that the document size doesn’t increase the size allocated on the disk. Capped collections are best for storing log information, cache data, or any other high-volume data.

Creating Capped Collection

To create a capped collection, we use the traditional createCollection command but with capped option as true and specifying the utmost size of collection in bytes.
>db.createCollection(“cappedLogCollection”,{capped:true,size:10000})
In addition to collection size, we can also limit the number of documents in the collection using the max parameter −
>db.createCollection(“cappedLogCollection”,{capped:true,size:10000,max:1000})
If you want to check whether a collection is capped or not, use the subsequent isCapped command −
>db.cappedLogCollection.isCapped()
If there’san existing collection which you are planning to convert to capped, you can do it with the subsequent code −
>db.runCommand({“convertToCapped”:”posts”,size:10000})
This code would convert our existing collection posts to a capped collection.

Querying Capped Collection

By default, a find query on a capped collection will display results in insertion order. But if you want the documents to be retrieved in reverse order, use the sort command as shown in the subsequent code −
>db.cappedLogCollection.find().sort({$natural:-1})
There are few other important points regarding capped collections worth knowing −
• We cannot delete documents from a capped collection.
• There are no default indexes present in a capped collection, not even on _id field.
• While inserting a new document, MongoDB doesn’t have to actually look for a place to accommodate new document on the disk. It can blindly insert the new document at the tail of the collection. This makes insert operations in capped collections very fast.
• Similarly, while reading documents MongoDB returns the documents in the same order as present on disk. This makes the read operation very fast.

MongoDB – Auto-Increment Sequence

MongoDB doesn’t have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents. However, there may be scenarios where we may want the _id field to have some auto-incremented value other than the ObjectId.
Since this is often not a default feature in MongoDB, we will programmatically achieve this functionality by employing a counters collection as suggested by the MongoDB documentation.

Using Counter Collection

Consider the subsequent products document. We want the _id field to be an auto-incremented integer sequence starting from 1,2,3,4 upto n.
{
“_id”:1,
“product_name”: “Apple iPhone”,
“category”: “mobiles”
}
For this, create a counters collection, which will keep track of the last sequence value for all the sequence fields.
>db.createCollection(“counters”)
Now, we will insert the subsequent document in the counters collection with productid as its key −
{
“_id”:”productid”,
“sequence_value”: 0
}
The field sequence_value keeps track of the last value of the sequence.
Use the subsequent code to insert this sequence document in the counters collection −
>db.counters.insert({_id:”productid”,sequence_value:0})

Creating Javascript Function

Now, we will create a function getNextSequenceValue which will take the sequence name as its input, increment the sequence number by 1 and return the updated sequence number. In our case, the sequence name is productid.
>function getNextSequenceValue(sequenceName){

var sequenceDocument = db.counters.findAndModify({
query:{_id: sequenceName },
update: {$inc:{sequence_value:1}},
new:true
});

return sequenceDocument.sequence_value;
}

Using the Javascript Function

We will now use the function getNextSequenceValue while creating a new document and assigning the returned sequence value as document’s _id field.
Insert two sample documents using the subsequent code −
>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 have used the getNextSequenceValue function to set value for the _id field.
To verify the functionality, let us fetch the documents using find command −
>db.products.find()
The above query returned the subsequent documents having the auto-incremented _id field −
{ “_id” : 1, “product_name” : “Apple iPhone”, “category” : “mobiles”}

{ “_id” : 2, “product_name” : “Samsung S3”, “category” : “mobiles” }

So, this brings us to the end of blog. This Tecklearn ‘Concept of Capped Collections and Auto-Increment Sequence in MongoDB’ helps you with commonly asked questions if you are looking out for a job in MongoDB and No-SQL Database Domain.
If you wish to learn and build a career in MongoDB or No-SQL Database domain, then check out our interactive, MongoDB Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

MongoDB Training

MongoDB Training

About the Course

Tecklearn’s MongoDB Training helps you to master the NoSQL database. The course makes you job-ready by letting you comprehend schema design, data modelling, replication, and query with MongoDB through real-time examples. Along with this, you’ll also gain hands-on expertise in installing, configuring, and maintaining the MongoDB environment, including monitoring and operational strategies from this online MongoDB training. Upon completion of this online training, you will hold a solid understanding and hands-on experience with MongoDB.

Why Should you take MongoDB Training?

• MongoDB – a $36 billion to a $40 billion market growing at 8% to 9% annually – Forbes.com
• Average salary of a Mongo DB certified professional is $134k – Indeed.com
• MongoDB has more than 900 customers, including 27 Fortune 100 companies like Cisco, eBay, eHarmony, MetLife & Salesforce.com

What you will Learn in this Course?

Introduction to MongoDB and Importance of NoSQL
• Understanding the basic concepts of RDBMS
• What is NoSQL Database and its significance?
• Challenges of RDBMS and How NoSQL suits Big Data needs
• Types of NoSQL Database and NoSQL vs. SQL Comparison
• CAP Theorem and Implementing NoSQL
• Introduction to MongoDB and its advantages
• Design Goals for MongoDB Server and Database, MongoDB tools
• Collection, Documents and Key Value Pair
• Introduction to JSON and BSON documents
• MongoDB installation
MongoDB Installation
• MongoDB Installation
• Basic MongoDB commands and operations,
• Mongo Chef (MongoGUI) Installation
Schema Design and Data Modelling
• Why Data Modelling?
• Data Modelling Approach
• Data Modelling Concepts
• Difference between MongoDB and RDBMS modelling
• Challenges for Data Modelling
• Model Relationships between Documents
• Data Model Examples and Patterns
• Model Tree Structures
CRUD Operations
• MongoDB Architecture
• CRUD Introduction and MongoDB CRUD Concepts
• MongoDB CRUD Concerns (Read and Write Operations)
• Cursor Query Optimizations and Query Behaviour in MongoDB
• Distributed Read and Write Queries
• MongoDB Datatypes
Indexing and Aggregation Framework
• Concepts of Data aggregation and types and data indexing concepts
• Introduction to Aggregation
• Approach to Aggregation
• Types of Aggregation: Pipeline, MapReduce and Single Purpose
• Performance Tuning
MongoDB Administration
• Administration concepts in MongoDB
• MongoDB Administration activities: Health check, recovery, backup, database sharing and profiling, performance tuning etc.
• Backup and Recovery Methods for MongoDB
• Export and Import of Data from MongoDB
• Run time configuration of MongoDB
MongoDB Security
• Security Introduction
• MongoDB security Concepts and security approach
• MongoDB integration with Java and Robomongo
Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Concept of Capped Collections and Auto-Increment Sequence in MongoDB"

Leave a Message

Your email address will not be published. Required fields are marked *