MongoDB: Collections
Subject: nodejs
MongoDB: Collections
In MongoDB, a collection is a grouping of related documents. It is the equivalent of a "table" in relational databases. Unlike tables, however, collections in MongoDB do not enforce a fixed schema, meaning documents within the same collection can have different fields and structures.
Why Use Collections? / Key Characteristics
Collections are fundamental for organizing your data efficiently in MongoDB:
- Document Storage: They are the primary containers for your BSON documents.
- Flexible Schema: Documents within a single collection can have varying structures. This allows for rapid iteration and adaptation to changing data requirements without complex schema migrations.
- Implicit Creation: A collection does not need to be explicitly defined. It is automatically created when the first document is inserted into it.
- Indexing: You can define indexes on fields within collections to improve query performance.
Core Concept: Document
A document is the basic unit of data in MongoDB, stored in a BSON (Binary JSON) format. Each document is a set of key-value pairs, similar to JSON objects. Documents are schema-less, meaning their structure can vary within a collection.
Basic Operations on Collections (Node.js Example)
Interacting with collections primarily involves CRUD (Create, Read, Update, Delete) operations on their documents.
Prerequisites:
- A running MongoDB instance (local or Atlas)
- Node.js installed
- MongoDB Node.js driver installed:
Example: Implicit Collection Creation and Inserting a Document
Explanation of the Code
require('mongodb').MongoClient;
: Imports the MongoDB client.url = "mongodb://localhost:27017/";
: Connection string to the MongoDB server.MongoClient.connect(...)
: Establishes the connection.client.db("mydb")
: Accesses themydb
database.db.collection("customers").insertOne(...)
: Selects or implicitly creates thecustomers
collection and inserts a document into it.client.close();
: Closes the MongoDB connection.
Expected Output
To run this program:
- Save the file as
collection_example.js
- Open your terminal in the same directory
- Ensure your MongoDB server is running
- Run:
Output:
You can verify the result in mongosh
:
Other Common Operations (Conceptual)
- Explicit Creation (rare):
- Find Documents:
- Update Document:
- Delete Document:
Key Takeaways
- A MongoDB Collection is a grouping of BSON documents, analogous to a table but with a flexible schema.
- Collections are implicitly created the first time a document is inserted.
- CRUD operations are the primary way to interact with collections via MongoDB drivers or the shell.
- Flexible schemas allow documents with varying structures in the same collection, providing high agility for application data modeling.