Database creation, collection management, and authorization

Creating Databases and Collections

Now that you understand documents, it's time to organize them. In MongoDB, documents live in collections, and collections live inside databases. This lesson covers creating, managing, and securing both.

1. Creating a Database

MongoDB uses a "create on first write" approach — a database isn't physically created until it has at least one collection with a document.

use ecommerceDB
db.products.insertOne({ name: "Wireless Mouse", price: 799 })
// Now ecommerceDB exists and appears in `show dbs`

2. Creating Collections

Collections can be created implicitly (on first insert) or explicitly with configuration options.

// Implicit creation
db.orders.insertOne({ orderId: 1001, total: 2499 })

// Explicit creation with options
db.createCollection("logs", {
  capped: true,
  size: 5242880,   // 5MB max size
  max: 5000         // Max 5000 documents
})
CommandPurpose
db.createCollection(name)Explicitly create a collection
show collectionsList all collections
db.collection.drop()Delete a collection
db.dropDatabase()Delete the current database
db.collection.renameCollection(newName)Rename a collection

3. Capped Collections

Capped collections are fixed-size collections that maintain insertion order and automatically overwrite the oldest documents once the size limit is reached — ideal for logs and caches.

4. User Authorization and Access Control

MongoDB uses role-based access control (RBAC) to manage who can create, read, or modify databases and collections.

use admin
db.createUser({
  user: "appUser",
  pwd: "strongPassword123",
  roles: [
    { role: "readWrite", db: "ecommerceDB" }
  ]
})
Built-in RoleAccess Level
readRead-only access to a database
readWriteRead and write access
dbAdminSchema and index administration
userAdminManage users and roles
rootFull superuser access (all databases)
Pro Tip: Follow the principle of least privilege — grant application users only readWrite on their specific database, never root.

5. Databases and Collections Checklist

  • ✅ Understand implicit vs explicit creation
  • ✅ Know how capped collections work
  • ✅ Create a database user with a scoped role
  • ✅ Practice dropping and renaming collections safely
Key Takeaway: Databases and collections are lightweight and flexible in MongoDB, but authorization still matters — always scope user permissions carefully, even in development.

Ready to master MongoDB?

Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.

Explore Course