MongoDB Create Collection

Whats is Meant by Collection

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”
}

 

Example of a collection

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 TrainingThis course will help you to achieve excellence in this domain. 

MongoDB creates collections when we first store the data in the collection.

 MindMajix YouTube Channel

Create Collection in MongoDB

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
cappedbooleanOptional. To create a capped collection. If users must set the maximum size in the size field.
autoIndexIdbooleanUsed for automatic creation of an index on the _id field. Deprecated from version 3.2.
sizenumberOptional. Specify a maximum size in bytes for a capped collection.
maxnumberOptional. The maximum number of documents allowed in the capped collection.
usePowerOf2SizesbooleanOptional
noPaddingbooleanOptional
storageEnginedocumentOptional
validatordocumentOptional. Allows users to specify validation rules or expressions for the collection.
validationLevelstringOptional. Determines how strictly MongoDB applies the validation rules to existing documents during an update.
validationActionstringOptional. Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted.
indexOtionDefaultsdocumentOptional. Allows users to specify a default configuration for indexes when creating a collection.
viewOnstringThe name of the source collection or view from which to create the view.
pipelinearrayAn array that consists of the aggregation pipeline stage. db.createView creates the view by applying the specified pipeline to the viewOn collection or view.
collationdocumentSpecifies the default collation for the collection.

Creating a collection using Javascript

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();
 });
});

List all collections

You can list all collections in a database with the following command.

  • db.getCollectionNames() – JS Shell
  • db.listCollections() – Node JS
  • show collections –Mongo Shell

Checkout MongoDB Interview Questions

Capped Collection

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.

Checkout MongoDB Tutorial

Creating a 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;
  });
 }
});
});
Course Schedule
NameDates
MongoDB Training Nov 02 to Nov 17View Details
MongoDB Training Nov 05 to Nov 20View Details
MongoDB Training Nov 09 to Nov 24View Details
MongoDB Training Nov 12 to Nov 27View Details
Last updated: 03 Apr 2023
About Author

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.

read less