Skip to main content

Databases & Collections

In MongoDB, data is organized in a hierarchy:
  1. Database: Container for collections.
  2. Collection: Container for documents (analogous to a Table in SQL).
  3. Document: The actual data record (analogous to a Row in SQL).

Creating a Database

In MongoDB, you don’t explicitly “create” a database. You just switch to a non-existent database and insert data, and it will be created automatically. Using mongosh (MongoDB Shell):
use myNewDatabase

Creating a Collection

Similarly, collections are created when you first insert data into them.
db.myCollection.insertOne({ x: 1 })
You can also explicitly create a collection if you need to set specific options (like validation rules or capped collections).
db.createCollection("users")

Dropping

Drop Database

use myDatabase
db.dropDatabase()

Drop Collection

db.myCollection.drop()

Document Structure

Documents are BSON objects.
{
  "_id": ObjectId("507f1f77bcf86cd799439011"),
  "name": "Alice",
  "age": 25,
  "address": {
    "street": "123 Main St",
    "city": "Wonderland"
  },
  "hobbies": ["reading", "coding"]
}

The _id Field

Every document must have a unique _id field.
  • If you don’t provide one, MongoDB generates a unique ObjectId automatically.
  • It is the primary key for the document.
  • It is immutable (cannot be changed).

Summary

  • Databases hold collections.
  • Collections hold documents.
  • Documents are the data records (JSON/BSON).
  • Databases and collections are created lazily (when data is inserted).
  • Every document has a unique _id.