Databases & Collections
In MongoDB, data is organized in a hierarchy:- Database: Container for collections.
- Collection: Container for documents (analogous to a Table in SQL).
- 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. Usingmongosh (MongoDB Shell):
Creating a Collection
Similarly, collections are created when you first insert data into them.Dropping
Drop Database
Drop Collection
Document Structure
Documents are BSON objects.The _id Field
Every document must have a unique _id field.
- If you don’t provide one, MongoDB generates a unique
ObjectIdautomatically. - 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.