Try Studio 3T for Free
  1. Knowledge Base
  2. MongoDB Tutorials
  3. A Beginner’s Guide to MongoDB Collections

A Beginner’s Guide to MongoDB Collections

A collection in MongoDB is a group of documents.

Collections in a NoSQL database like MongoDB correspond to tables in relational database management systems (RDBMS) or SQL databases.  As such, collections don’t enforce a set schema, and documents within a single collection can have widely different fields.

What’s in a MongoDB document? Learn about it in our Beginner’s Guide.

Create a Collection – db.createCollection()

Creating a collection in mongo Shell is done through the db.createCollection() method.

A collection can be created with or without set parameters, which include size (maximum size of a document in bytes).

Without parameters:

db.createCollection(
          "sea_mammals",
)

With parameters, in this case “max” (maximum number of documents):

db.createCollection(
          "sea_mammals",
       {
         max: 300,
       }
)

For further reading check out How to Limit MongoDB Collection Size

Drop a Collection – drop()

Removing a collection from the database is done through the drop() method.  Leaving the field blank deletes the entire collection, like so:

db.manatees.drop(
)

Rename a Collection – renameCollection()

To rename a collection simply use the renameCollection() method, specifying the target name in brackets:

db.sea_mammels.renameCollection(
          "sea_mammals",
)

View a Collection’s Size – totalSize()

To determine a collection’s size, use the totalSize() method:

db.sea_mammals.totalSize(
)

It returns the collection’s total storage size, plus the total size of each of the collection’s indexes in bytes.

View a Collection’s Document Count – count()

To count the number of documents in a collection, or the number of documents a find query would return, use the count() method.

Total document count:

db.sea_mammals.count(
)

Count for documents matching manatee:

db.sea_mammals.count(
          {
             pet: "manatee",
          }
)

View a Collection’s Stats – stats()

To view a collection’s overall stats (including size and document count), use the stats() method. Size data by default is returned in bytes but can be modified with the scale value, in this case kilobytes at by specifying 1024:

db.sea_mammals.stats(
          { 
             scale: 1024,
          }
)
Updated on December 5, 2019

Was this article helpful?

Related Articles