Creation and deletion of sets
Collection Creation
In MongoDB, collections are created implicitly. When a document is first inserted into a non-existent collection, the system automatically creates that collection. This design simplifies the development process, but collections can also be explicitly created using the createCollection()
method.
Syntax for explicit collection creation:
db.createCollection(name, options)
Common option parameters:
capped
: Boolean, whether to create a capped collectionsize
: Numeric, maximum size of the capped collection in bytesmax
: Numeric, maximum number of documents allowed in the capped collectionvalidator
: Document, validation rulesvalidationLevel
: String, validation levelvalidationAction
: String, action to take when validation fails
Example of creating a regular collection:
// Create a regular collection
db.createCollection("products")
// Create a collection with validation
db.createCollection("employees", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "position"],
properties: {
name: { bsonType: "string" },
position: { bsonType: "string" },
salary: { bsonType: "double" }
}
}
}
})
Example of creating a capped collection:
// Create a capped collection with a maximum of 100MB and 1000 documents
db.createCollection("logs", {
capped: true,
size: 104857600,
max: 1000
})
Collection Deletion
To delete a collection, use the drop()
method. This permanently removes the collection along with all its documents, indexes, and associated metadata.
Basic syntax:
db.collection.drop()
Example of deleting a collection:
// Delete the products collection
db.products.drop()
// Check if the collection exists before deleting
if(db.getCollectionNames().includes("tempData")) {
db.tempData.drop()
}
Notes on collection deletion:
- The operation is irreversible, and data will be permanently lost
- Requires write permissions on the database
- In a sharded cluster, the deletion operation propagates to all shards
- System collections (e.g., system.*) usually cannot be deleted
Collection Inspection and Listing
Before operating on a collection, it is often necessary to check if it exists or to list all collections in the database.
Check if a collection exists:
// Method 1: Check if the collection name is in the list of collections
db.getCollectionNames().includes("users")
// Method 2: Use the listCollections command
db.getCollectionInfos({name: "users"})
Get a list of all collections:
// Get the names of all collections in the current database
show collections
// Programmatically get the list of collections
db.getCollectionNames()
// Get detailed information about collections
db.getCollectionInfos()
Collection Renaming
The renameCollection()
method can be used to rename a collection, which is useful when restructuring the database.
Syntax:
db.collection.renameCollection(target, dropTarget)
Parameter description:
target
: New collection namedropTarget
: Optional, Boolean, whether to delete the target collection if it exists
Example:
// Rename customers to clients
db.customers.renameCollection("clients")
// Force rename, overwriting the existing target collection
db.oldData.renameCollection("newData", true)
Notes:
- The operation requires read permissions on the source collection and write permissions on the target collection
- Collections cannot be renamed in a sharded cluster
- Renaming preserves the original collection's indexes and options
Modifying Collection Options
After creating a collection, certain options can be modified using the collMod
command.
Common modifiable options:
- Validation rules (validator)
- Validation level (validationLevel)
- Validation action (validationAction)
- Index options
Example:
// Modify the collection's validation rules
db.runCommand({
collMod: "employees",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "department"],
properties: {
name: { bsonType: "string" },
department: { bsonType: "string" },
hireDate: { bsonType: "date" }
}
}
},
validationAction: "warn"
})
Collection Statistics
Obtaining collection statistics helps understand usage patterns and performance characteristics.
Common statistics commands:
// Get basic collection statistics
db.collection.stats()
// Get collection storage statistics
db.collection.storageSize()
// Get total collection size
db.collection.totalSize()
// Get collection index size
db.collection.totalIndexSize()
Example output analysis:
const stats = db.orders.stats()
console.log(`Collection size: ${stats.size} bytes`)
console.log(`Document count: ${stats.count}`)
console.log(`Average document size: ${stats.avgObjSize} bytes`)
console.log(`Storage size: ${stats.storageSize} bytes`)
console.log(`Number of indexes: ${stats.nindexes}`)
Collection Cloning and Copying
In some scenarios, it is necessary to copy collection structures or data to other collections.
Copy collection data:
// Simple copy of all documents
db.sourceCollection.find().forEach(function(doc) {
db.targetCollection.insert(doc)
})
// Use an aggregation pipeline to process before copying
db.sourceCollection.aggregate([...]).forEach(function(doc) {
db.targetCollection.insert(doc)
})
Clone a collection (including indexes):
// Clone a collection to the same database
db.sourceCollection.aggregate([{ $out: "clonedCollection" }])
// Clone to another database
db.sourceCollection.aggregate([{ $out: { db: "otherDB", coll: "clonedCollection" } }])
Collection Import and Export
MongoDB provides tools and commands to import and export collection data.
Using mongoimport/mongoexport tools:
# Export a collection as JSON
mongoexport --db test --collection products --out products.json
# Import a collection from JSON
mongoimport --db test --collection products --file products.json
Programmatic export and import:
// Export to a JSON file
const fs = require('fs')
const docs = db.products.find().toArray()
fs.writeFileSync('products.json', JSON.stringify(docs))
// Import from a JSON file
const data = JSON.parse(fs.readFileSync('products.json'))
db.products.insertMany(data)
Special Collection Operations
MongoDB also provides some special collection operation commands.
Compact a collection (WiredTiger storage engine):
db.runCommand({ compact: "largeCollection" })
Convert a collection to a capped collection:
db.runCommand({
convertToCapped: "logs",
size: 1048576
})
Rebuild a collection (similar to SQL's TRUNCATE):
// Method 1: Delete and recreate
db.tempData.drop()
db.createCollection("tempData")
// Method 2: Use deleteMany to remove all documents
db.tempData.deleteMany({})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:数据库的创建与删除