SyntaxStudy
Sign Up
MongoDB Beginner 1 min read

Collections and Documents

In MongoDB, data is organised into collections, which are analogous to tables in a relational database. A collection holds documents, and each document is a BSON object identified by a unique _id field. If you do not supply an _id, MongoDB automatically generates an ObjectId, which encodes the creation timestamp, machine ID, and a random sequence. Documents within the same collection do not need identical structures, though in practice most applications maintain a consistent shape. Collections are created implicitly the first time you insert a document, so there is no need for a CREATE TABLE statement. You can also create capped collections with a fixed size, which automatically expire the oldest documents when the size limit is reached — useful for log data or event streams.
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