MongoDB Collection

A collection is MongoDB's equivalent of a table — a named group of documents that can be created implicitly by an insert or explicitly with configuration options.

What Is a Collection?

A collection groups documents that represent the same kind of entity in your application, such as users, orders, or products. Collections live inside a database and, unlike SQL tables, do not enforce a fixed schema by default — one document can have fields another one lacks entirely, which makes collections a natural fit for evolving data models.

Implicit vs Explicit Collection Creation

Most of the time you never explicitly create a collection — calling insertOne() or insertMany() against a collection name that doesn't exist yet creates it automatically with default settings. You reach for explicit creation, using db.createCollection(), only when you need extra configuration up front, such as a maximum size, a fixed document order, or a validation schema.

OptionPurpose
cappedfixes the collection to a maximum size, overwriting oldest documents
sizemaximum size in bytes for a capped collection
maxmaximum number of documents in a capped collection
validatora JSON Schema or query expression documents must satisfy
validationLevelcontrols whether validation applies to inserts, updates, or both

Managing Collections

  • db.createCollection(name, options) — create a collection explicitly
  • show collections — list collections in the current database
  • db.collection.renameCollection(newName) — rename a collection
  • db.collection.drop() — delete a collection and all its documents
  • db.getCollectionInfos() — inspect collection metadata and options

Create a collection with a validator

db.createCollection("reviews", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["rating", "comment"],
      properties: {
        rating: { bsonType: "int", minimum: 1, maximum: 5 },
        comment: { bsonType: "string" }
      }
    }
  }
})
Note: Schema validation is opt-in. Without a validator, MongoDB accepts any well-formed BSON document into a collection, which is why the document model is often described as flexible or schema-less by default.

Create a capped collection

db.createCollection("activity_log", {
  capped: true,
  size: 5242880,
  max: 1000
})

List and drop collections

show collections
db.activity_log.drop()
Note: Collection names can include letters, numbers, and underscores, but conventionally use lowercase, plural nouns like orders or products to mirror the many documents they hold.

Exercise: MongoDB Collection

What happens if you insert a document into a collection that doesn't exist yet?