MongoDb - MongoDB collections
1. What is a Collection?
-
In MongoDB, a collection is the equivalent of a table in relational databases.
-
A collection holds documents (JSON-like objects), but unlike SQL tables:
-
Documents in a collection don’t need to have the same fields.
-
The schema is flexible (schema-less by default).
-
-
Collections live inside databases.
Example:
-
Database:
myDatabase
-
Collection:
users
-
Documents:
{ "name": "Alice", "age": 25 } { "username": "bob123", "email": "[email protected]" }
Notice: The documents don’t need identical fields.
2. Creating a Collection
a) Explicitly
db.createCollection("users")
You can also pass options:
db.createCollection("logs", {
capped: true, // fixed size collection
size: 5242880, // size in bytes (5 MB)
max: 5000 // maximum number of documents
})
b) Implicitly
MongoDB automatically creates a collection the first time you insert a document:
db.products.insertOne({ name: "Laptop", price: 1200 })
This creates products
collection if it doesn’t exist yet.
3. Basic Operations on Collections
a) Insert Documents
db.users.insertOne({ name: "Alice", age: 25 })
db.users.insertMany([
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 22 }
])
b) Query Documents
db.users.find({ age: { $gt: 25 } })
db.users.findOne({ name: "Alice" })
c) Update Documents
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26 } }
)
db.users.updateMany(
{ age: { $lt: 25 } },
{ $set: { status: "young" } }
)
d) Delete Documents
db.users.deleteOne({ name: "Charlie" })
db.users.deleteMany({ inactive: true })
4. Viewing Collections
List all collections in the current database:
show collections
or:
db.getCollectionNames()
5. Dropping a Collection
Remove a collection completely:
db.users.drop()
6. Special Types of Collections
-
Capped collections → fixed size, old docs automatically overwritten (useful for logs).
-
Time-series collections → optimized for time-based data (IoT, events, metrics).
-
View collections → like SQL views, based on aggregation pipelines.
Example (time-series):
db.createCollection("sensorData", {
timeseries: { timeField: "timestamp", metaField: "sensorId" }
})