Collections are like tables in a NoSQL database system like MongoDB. The data records are BSON documents stored in collections inside a database. BSON stands for Binary JSON. Collections store documents.
Documents are the unit of data stored in collections. Collections can store document which is not same in structure because MongoDB is schema-free DBMS.
{ “name” : “John”, “age” : 22, “email” : “example@gmail.com” }
A collection name must start with _ (underscore) or letters. A collection name can contain a number but not in the first space. A collection name can’t contain the “$” symbol. The maximum length for a collection is 128 characters.
If you want to enrich your career and become a professional in MongoDB, then visit Mindmajix - a global online training platform: "MongoDB Training" This course will help you to achieve excellence in this domain.
MongoDB creates collections when we first store the data in the collection.
db.createCollection()
method is used to explicitly create a collection. Collections do not need a schema.
db.createCollection()
the method takes the following arguments.
Fields
|
Type
|
Description
|
capped | boolean | Optional. To create a capped collection. If users must set the maximum size in the size field. |
autoIndexId | boolean | Used for automatic creation of an index on the _id field. Deprecated from version 3.2. |
size | number | Optional. Specify a maximum size in bytes for a capped collection. |
max | number | Optional. The maximum number of documents allowed in the capped collection. |
usePowerOf2Sizes | boolean | Optional |
noPadding | boolean | Optional |
storageEngine | document | Optional |
validator | document | Optional. Allows users to specify validation rules or expressions for the collection. |
validationLevel | string | Optional. Determines how strictly MongoDB applies the validation rules to existing documents during an update. |
validationAction | string | Optional. Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted. |
indexOtionDefaults | document | Optional. Allows users to specify a default configuration for indexes when creating a collection. |
viewOn | string | The name of the source collection or view from which to create the view. |
pipeline | array | An array that consists of the aggregation pipeline stage. db.createView creates the view by applying the specified pipeline to the viewOn collection or view. |
collation | document | Specifies the default collation for the collection. |
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
You can list all collections in a database with the following command.
Checkout MongoDB Interview Questions
MongoDB can apply a size limit on a collection. These collections are called a capped collection. Capped collections are implemented using a circular queue and used for high throughput operations. When the size limit reaches mongo DB overwrite older documents to make space for new documents without the explicit use of any command.
Capped collections are suitable for storing a high volume of data that needs to be refreshed periodically like log data and cache data. Capped collection store document in order of disk storage hence use some restriction. If a document size increases when updating it MongoDB will not update it.
Capped collections cannot be shared. Documents from the capped collection cannot be deleted and must use { emptycapped: nameOfCollection }
the command to empty the capped collection.
To create a capped collection db.createCollection() method is used with document option capped set to true and size must be defined in bytes.
db.createCollection( "logdata", { capped: true, size: 1024000 } )
to set a max number of a document we can use the max option also
db.createCollection( "log", { capped: true, size: 100000, max: 2000 } )
To convert a collection to capped collection we can use the below command
db.runCommand({"convertToCapped": "logdata", size: 1024000});
In capped collection there is no default index present.
The capped collection can be used to handle failure scenario. To rollback activities using capped collection because it guarantees the insertion order.
Capped Collection operation in Javascript using node js
var MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server;
var mongoclient = new MongoClient(new Server(host, port));
var db = mongoclient.db(dbName);
db.open(function(err, db)
{
if (err) throw err;
var capped = db.collection('capped');
var document = {"foo": 1,"bar": 1}
capped.find().count(function(err, count)
{
if (err) throw err;
if (count === 0)
{
console.log("Creating collection...");
db.createCollection("capped", {"capped": true,"size": 100000,"max": 5000}, function(err, collection) {
if (err) throw err;
console.log("Inserting document...");
collection.insert(document, function(err, result) {
if (err) throw err;
});
});
} else {
console.log("Inserting document without creating collection...");
capped.insert(document, function(err, result) {
if (err) throw err;
});
}
});
});
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
MongoDB Training | Dec 24 to Jan 08 | View Details |
MongoDB Training | Dec 28 to Jan 12 | View Details |
MongoDB Training | Dec 31 to Jan 15 | View Details |
MongoDB Training | Jan 04 to Jan 19 | View Details |
Prasanthi is an expert writer in MongoDB, and has written for various reputable online and print publications. At present, she is working for MindMajix, and writes content not only on MongoDB, but also on Sharepoint, Uipath, and AWS.