I. What is a MongoDB Collection?¶
In MongoDB, a Collection is equivalent to a “table” in a relational database, but it stores Documents (JSON-like structures). Unlike tables, documents in a collection do not require a fixed field structure—different documents can contain different fields, making it highly flexible.
II. Creating a Collection¶
There are two ways to create a collection: explicit creation (manually via commands) and implicit creation (automatically created when inserting data).
1. Explicit Collection Creation (createCollection())¶
Use the db.createCollection(collectionName) command to manually create a collection. For example, create a collection named students:
// Execute in the MongoDB Shell
db.createCollection("students")
- If successful, it returns
{ "ok" : 1 }, indicating the collection was created. - Optional Parameters: You can set collection properties like
capped(fixed-size collection, old data auto-deleted) orsize(maximum size in bytes). For example, create a fixed-size log collection:
db.createCollection("logs", { capped: true, size: 10000 })
(Note: capped: true enables fixed size, and size: 10000 sets a maximum of 10KB; old data will be overwritten when exceeded.)
2. Implicit Collection Creation (Auto-created on Insert)¶
If you insert data into a non-existent collection, MongoDB automatically creates it. For example, directly insert a document into the non-existent students collection:
db.students.insertOne({ name: "Alice", age: 20 })
The students collection will be automatically created, and the inserted document will be stored.
III. Deleting a Collection (drop())¶
Use the db.collectionName.drop() command to delete a collection. This permanently removes the collection and all its data (no recycle bin), so proceed with caution!
Syntax:
db.collectionName.drop()
- Returns
trueif the collection exists and is successfully deleted; returnsfalseif the collection does not exist or deletion fails.
Example:
// Delete the "students" collection
db.students.drop() // Returns true on success, false otherwise
IV. Data Insertion (insertOne()/insertMany())¶
MongoDB uses insertOne() (single document) and insertMany() (multiple documents) to insert data. Documents are in key-value pair format (similar to JSON) and automatically generate a unique _id field (customizable but recommended to use MongoDB’s auto-generated value).
1. Inserting a Single Document (insertOne())¶
Syntax:
db.collectionName.insertOne(documentObject)
- Example: Insert student information into the
studentscollection:
db.students.insertOne({
name: "Bob",
age: 22,
major: "Computer Science",
hobbies: ["reading", "coding"] // Array type
})
- Return Result:
{
acknowledged: true,
insertedId: ObjectId("60d21b4667d0d8992e610c85") // MongoDB auto-generated unique ID
}
2. Inserting Multiple Documents (insertMany())¶
Syntax:
db.collectionName.insertMany([document1, document2, ...])
- Example: Insert two student records:
db.students.insertMany([
{ name: "Charlie", age: 21, major: "Mathematics" },
{ name: "Diana", age: 23, major: "Physics", isHonorStudent: true } // New field allowed
])
- Return Result:
{
acknowledged: true,
insertedIds: [
ObjectId("60d21b4667d0d8992e610c86"),
ObjectId("60d21b4667d0d8992e610c87")
]
}
V. Notes¶
- Collection Naming: Case-sensitive, and avoid special characters (except legal symbols like
$or.). - Data Types: Documents support flexible types: strings in quotes (e.g.,
name: "Bob"), numbers directly (e.g.,age: 20), and dates vianew Date()(e.g.,birth: new Date("2000-01-01")). - Uniqueness:
insertOne()/insertMany()auto-generate_idto ensure uniqueness within a collection (duplicate fields are allowed). - Irreversible Deletion:
drop()permanently deletes data; back up data before deletion.
VI. Summary¶
- Create: Explicitly with
createCollection(), or implicitly by inserting data. - Delete: Use
drop(), which permanently removes data with no recovery option. - Insert: Single documents with
insertOne(), multiple documents withinsertMany(), using key-value pair format.
With these operations, you’ve mastered the basics of collection management and data insertion in MongoDB. Try practicing in the MongoDB Shell or a visualization tool (e.g., Robo 3T) to reinforce your understanding!