Lesson

MongoDB Create Collection

10 min reading
Free Course

MongoDB Create Collection: Explicit Setup, Validation, and Indexes

Although MongoDB creates a collection automatically the first time you insert a document, calling db.createCollection() explicitly lets you attach JSON Schema validation rules, configure capped collections, or create unique indexes before traffic hits your app.

Creating a Collection with Schema Validation and Unique Indexes

Adding $jsonSchema rules inside createCollection() forces MongoDB to reject malformed documents—like a users record missing an email—even if multiple services write to the same database. Pairing that with createIndex({ email: 1 }, { unique: true }) guarantees uniqueness at the database level.

import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017');

async function setupUsersCollection() {
  try {
    await client.connect();
    const db = client.db('kodersolution_store');

    const existing = await db.listCollections({ name: 'users' }).toArray();
    if (existing.length === 0) {
      await db.createCollection('users', {
        validator: {
          $jsonSchema: {
            bsonType: 'object',
            required: ['email', 'fullName'],
            properties: {
              email: { bsonType: 'string' },
              fullName: { bsonType: 'string' },
            },
          },
        },
      });
    }

    await db.collection('users').createIndex({ email: 1 }, { unique: true });
    console.log('Users collection and unique email index verified.');
  } finally {
    await client.close();
  }
}

setupUsersCollection().catch((err) => console.error('Collection setup error:', err.message));

When to Use Capped or Time-Series Collections

For fixed-size circular logs, capped: true with size and max keeps disk usage bounded automatically. For IoT metrics or clickstream analytics, { timeseries: { timeField: 'timestamp' } } optimizes storage and date-range queries.

Common Mistakes to Avoid

  • Calling createCollection() unconditionally on startup without checking: Creating an existing collection throws NamespaceExists (code 48). Always inspect listCollections({ name }) first or handle error code 48.
  • Creating unique indexes after duplicate records already exist: createIndex({ email: 1 }, { unique: true }) fails with E11000 if duplicate emails are already in the collection. Create indexes during initial setup.
  • Indexing every field indiscriminately: Each extra index slows down insertOne and updateOne writes and consumes RAM. Index only fields queried or sorted frequently.

Frequently Asked Questions

Is db.createCollection() required before calling insertOne()?

No. db.collection('orders').insertOne(...) creates the 'orders' collection automatically if it does not exist yet.

How do I delete an entire collection in Node.js?

Call await db.collection('temp_logs').drop(), checking first that it exists or catching NamespaceNotFound.

Does createIndex() block if the index already exists with the same options?

No. createIndex() is idempotent—if the identical index already exists, MongoDB returns its name immediately without rebuilding it.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Node.js Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum