MongoDB
Beginner
1 min read
Collections and Documents
Example
// Create a collection explicitly (optional)
db.createCollection("users")
// Create a capped collection (fixed size, auto-deletes oldest)
db.createCollection("logs", { capped: true, size: 1048576, max: 1000 })
// Insert automatically creates the collection
db.products.insertOne({ name: "Laptop", price: 999.99 })
// List all collections
db.getCollectionNames()
// Get collection stats
db.users.stats()
// Rename a collection
db.users.renameCollection("customers")
// Drop a collection
db.customers.drop()
// Check the _id ObjectId components
let id = ObjectId("64a1f2b3c4d5e6f7a8b9c0d1")
id.getTimestamp() // ISODate("2023-07-02T...")
id.str // hex string