Sling Academy
Home/MongoDB/MongoDB: How to create/drop a collection (with examples)

MongoDB: How to create/drop a collection (with examples)

Last updated: February 02, 2024

Introduction

MongoDB, the popular NoSQL database, features a flexible schema that allows you to work without having to predefine the structure of your data. Collections in MongoDB are analogous to tables in relational databases and are a critical concept to understand when working with MongoDB.

In this tutorial, we’ll go through the steps of creating and dropping collections in MongoDB, complete with examples. We will progress from basic operations to more advanced options, providing you with a solid foundation in managing collections in MongoDB.

Prerequisites

  • MongoDB server installed and running.
  • Basic understanding of MongoDB commands and operations.
  • MongoDB shell or a MongoDB GUI Client for executing commands.

Creating a Collection

To create a collection in MongoDB, you have two main approaches:

  1. Implicit Creation
  2. Explicit Creation

Implicit Collection Creation

You can create a collection implicitly by inserting a document into what you intend to be a new collection. MongoDB will automatically create the collection if it does not yet exist.

db.createCollection("inventory")

Output:

{ "ok": 1 }

Explicit Collection Creation

If you need to set specific options on your collection like capped size or validation rules, you’ll need to create it explicitly using the createCollection command.

db.createCollection("inventory", {capped: true, size: 1024, max: 5})

Output:

{ "ok": 1 }

Dropping a Collection

When you no longer need a collection, you can remove it entirely from the database using the drop command. This action is irreversible.

db.inventory.drop()

Output:

true

Working with Capped Collections

Capped collections are fixed-size collections that support high-performance reads and writes. They maintain the insertion order and, once the specified size is reached, old data is overwritten.

Creating a Capped Collection

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

Output:

{ "ok": 1 }

Converting a Collection to Capped

You can convert an existing collection to a capped collection using the convertToCapped command.

db.runCommand({convertToCapped: "messages", size: 100000})

Output:

{ "ok": 1 }

Using Validation Rules

MongoDB allows you to enforce document structure using validation rules when creating a new collection.

Creating a Collection with Validation Rules

db.createCollection("orders", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["product_id", "quantity"],
      properties: {
        product_id: {
          bsonType: "int",
          description: "must be an integer and is required"
        },
        quantity: {
          bsonType: "int",
          minimum: 0,
          description: "must be an integer greater than 0 and is required"
        }
      }
    }
  }
})

Output:

{ "ok": 1 }

Index Management

Collections house your data but use indexes to facilitate quick search. After creating your collections, it is usual to create, modify, or remove indexes to improve search performance.

Creating an Index

db.inventory.createIndex({ item: 1 })

Output:

{ "createdCollectionAutomatically": false, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }

Dropping an Index

db.inventory.dropIndex("item_1")

Output:

{ "nIndexesWas": 2, "ok": 1 }

Conclusion

Throughout this tutorial, you’ve learned how to manage collections in MongoDB, which included creating, dropping, and customizing collections with various options such as capped settings and validation rules. Understanding collections is fundamental when designing and working with a MongoDB database.

Next Article: MongoDB: How to move a collection to a different database (4 ways)

Previous Article: MongoDB: 3 ways to view all collections in a database

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)