Create and Drop collections

Collections are MongoDB's containers for documents, roughly like tables: createCollection() makes one explicitly, but inserting a document creates it automatically, and drop() removes it.

8 min read · 8 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Where the documents live

You have the festdb database and a model for an event document. But documents do not float loose in a database: they live in collections. FestConnect will have an events collection, maybe a registrations collection, and so on.

A collection is roughly the NoSQL cousin of a relational TABLE from BCA205: a container for records of a similar kind. The big difference: a collection does NOT enforce a schema, so its documents can have different fields. This short lesson covers making and removing collections, which turns out to be delightfully easy, sometimes automatic.

Theory

Collection, and how it differs from a table

A collection is a group of documents, the rough equivalent of a table, with one liberating difference:

  • a relational table enforces a fixed schema: every row has the same columns
  • a MongoDB collection enforces NO schema: documents in it can have different fields

So FestConnect's events collection can hold the Garba document (with a dress code), the coding-contest document (with a language list), and the workshop document (with a materials list), all together, each its own shape. The collection groups them by KIND (they are all events), not by a rigid column layout.

Practical

Creating a collection, two ways, then dropping it

// Explicit creation:
db.createCollection("events")

// OR implicit (lazy) creation: inserting into a non-existent
// collection CREATES it automatically:
db.events.insertOne({ name: "Garba Night", seats: 350 })
// -> if 'events' did not exist, MongoDB just created it.

// List collections in the current database:
show collections

// Drop the collection and ALL its documents:
db.events.drop()   // returns true

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Quiz

You run db.events.insertOne({...}) but never created an 'events' collection first. What happens?

  1. An error: the collection must exist before inserting
  2. MongoDB creates the 'events' collection automatically (lazily) and inserts the document
  3. The document is lost with no collection to hold it
  4. You must run db.createCollection first, always
Show the answer

MongoDB creates the 'events' collection automatically (lazily) and inserts the document

MongoDB creates a collection IMPLICITLY (lazily) the first time you insert into a name that does not exist, so db.events.insertOne() creates 'events' and stores the document in one step: no error, no prior setup needed. This is why you rarely call db.createCollection() explicitly (you use it mainly for special options like a capped collection). Option A imposes a relational-style must-create-first rule that MongoDB does not have. Option C imagines data loss that does not occur. Option D overstates: createCollection is optional. The convenience: inserting a document is enough to bring its collection into being.

Think first

When would you use createCollection explicitly?

If inserting a document creates the collection automatically, why does db.createCollection() even exist? Then tap.

Show the answer

For cases where you need to set OPTIONS on the collection UP FRONT, before any data goes in. The main example is a CAPPED collection: a fixed-size collection that automatically overwrites its oldest documents when full (useful for logs or a rolling feed). You must createCollection with the capped option to get that behaviour; you cannot retrofit it by inserting. Other options (validation rules, specific configurations) similarly need explicit creation. So the rule of thumb: for ordinary collections, just insert and let MongoDB create it lazily; reach for createCollection() only when you need to configure the collection's behaviour before use. Most of the time, the automatic route is all you need.

Watch out

Collection traps

Assuming you must create collections first: inserting creates them automatically; explicit createCollection is usually unnecessary.

Expecting an enforced schema: collections are schema-flexible; documents can differ (you can ADD validation rules, but they are optional).

drop() is irreversible: db.events.drop() deletes the collection AND every document in it; be sure.

Typos create new collections: db.evnts.insertOne() silently creates an 'evnts' collection; a misspelt collection name does not error, it makes a new (wrong) collection.

Theory

Container ready; now fill and query it

With the events collection in place (created by a single insert), FestConnect can start storing and retrieving real data. The next lesson is the heart of MongoDB: CRUD, the four operations create (insert), read (find), update, and delete, plus the query and projection operators that let you fetch exactly the events you want. This is where MongoDB becomes genuinely useful.

Summary

Key takeaways

  • A collection is a group of documents: roughly a table, but with NO enforced schema (documents can differ).
  • db.createCollection('events') creates one explicitly (with optional settings like capped).
  • Inserting into a non-existent collection creates it AUTOMATICALLY (lazily): db.events.insertOne() creates 'events'.
  • show collections lists them; db.events.drop() removes the collection and all its documents.
  • You rarely need createCollection explicitly: use it only for options like capped collections.
  • A misspelt collection name silently creates a new (wrong) collection, no error.
  • Memory hook: inserting a document is enough to create its collection.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Concepts of NoSQL: MongoDB

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Create and Drop collections · Advance Web Designing (Major-11-01) · Gri-Learn