Blog

MongoDB Create Collection

  • (4.0)
  •   |   460 Ratings

Collection

Collections are like tables in a NoSQL database system like MongoDB. The data records are BSON document 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 are 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 number but not in first space. A collection name can’t contain “$” symbol. Maximum length for a collection is 128 characters.

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

Accelerate Your career with MongoDB Training and become expertise in MongoDB. Enroll For Free MongoDB Training Demo!

Create Collection

db.createCollection() method is use to explicitly create a collection. Collections do not need a schema.

db.createCollection() method takes following arguments.

Fields Type Description
capped boolean Optional. To create a capped collection. If used must set maximum size in 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.
Explore MongoDB Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Creating 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 data base with following command.

  1. db.getCollectionNames() – JS Shell

  2. db.listCollections() – Node JS

  3. show collections –Mongo Shell

Checkout MongoDB Interview Questions

Capped Collection

MongoDB can apply size limit on a collection. These collections are called as capped collection. Capped collections are implemented using circular queue and used for high throughput operations. When size limit reaches mongo db overwrite older documents to make space for new documents without explicit use of any command.

Capped collections are suitable for storing high volume of data which need 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 mongo db will not update it.

Capped collections cannot be sharded. Documents from capped collection cannot be deleted and must use { emptycapped: nameOfCollection } 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 define in bytes.

db.createCollection( "logdata", { capped: true, size: 1024000 } )

to set a max number of document we can use the max option also

db.createCollection( "log", { capped: true, size: 100000, max: 2000 } )

To covert a collection to capped collection we can use the below command

db.runCommand({"convertToCapped": "logdata", size: 1024000});

In cappedcollection there is no default index present.

Capped collection can be used 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;

  });

 }

 

});

});


Popular Courses in 2018

Get Updates on Tech posts, Interview & Certification questions and training schedules