阿里云主机折上折
  • 微信号
Current Site:Index > Creation and deletion of sets

Creation and deletion of sets

Author:Chuan Chen 阅读数:46947人阅读 分类: MongoDB

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 collection
  • size: Numeric, maximum size of the capped collection in bytes
  • max: Numeric, maximum number of documents allowed in the capped collection
  • validator: Document, validation rules
  • validationLevel: String, validation level
  • validationAction: 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:

  1. The operation is irreversible, and data will be permanently lost
  2. Requires write permissions on the database
  3. In a sharded cluster, the deletion operation propagates to all shards
  4. 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 name
  • dropTarget: 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:

  1. The operation requires read permissions on the source collection and write permissions on the target collection
  2. Collections cannot be renamed in a sharded cluster
  3. 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

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.