阿里云主机折上折
  • 微信号
Current Site:Index > The creation and deletion of databases

The creation and deletion of databases

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

Database Creation

In MongoDB, creating a database does not require explicit declaration. The database is automatically created when data is first written to a non-existent database. Use the use command to switch to or create a database:

// After connecting to MongoDB
use shopDB
// The database is actually created only after performing an insert operation
db.products.insertOne({name: "Laptop", price: 999})

Key features:

  1. Database names are case-sensitive, with a maximum of 64 characters.
  2. Reserved databases: admin, local, and config cannot be created directly.
  3. Naming restrictions: Cannot contain special characters such as /\. "$*<>:|?.

View all databases:

show dbs
// Newly created databases will only appear if they contain at least one collection.

Explicit Collection Creation

Although collections are automatically created when data is inserted, they can also be explicitly defined:

// Create a fixed-size collection (circular queue)
db.createCollection("logs", {
  capped: true,
  size: 100000,
  max: 500
})

// Create a collection with validation rules
db.createCollection("employees", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "position"],
      properties: {
        name: { bsonType: "string" },
        age: { bsonType: "int", minimum: 18 }
      }
    }
  }
})

Database Deletion

To delete a database, first switch to the target database:

use tempDB
db.dropDatabase()
// Returns { "ok" : 1 } upon success

Important notes:

  1. Deletion is irreversible.
  2. Requires write permissions on the database instance.
  3. Disk space is not immediately released after deletion.

Two ways to delete a collection:

// Method 1
db.orders.drop()

// Method 2 (with options)
db.runCommand({
  drop: "orders",
  writeConcern: { w: "majority" }
})

Batch Operation Example

Complete example for creating a test database:

// Create an e-commerce database
use ecommerce

// Batch create collections
const collections = ["users", "products", "orders"]
collections.forEach(col => {
  db.createCollection(col, {
    validator: {
      $jsonSchema: {
        bsonType: "object",
        required: ["_id"],
        properties: {
          _id: { bsonType: "objectId" }
        }
      }
    }
  })
})

// Insert initial data
db.users.insertMany([
  {_id: ObjectId(), name: "Alice", role: "admin"},
  {_id: ObjectId(), name: "Bob", role: "customer"}
])

// Complete process for deleting the entire database
use ecommerce
db.dropDatabase()

Permission Management

Permission control when creating a database:

// Create a user and assign roles
db.createUser({
  user: "shopAdmin",
  pwd: "securePass123",
  roles: [{
    role: "dbOwner",
    db: "shopDB"
  }]
})

// Permission verification required before deleting a database
use admin
db.auth("adminUser", "adminPass")
use shopDB
db.dropDatabase()

Special Scenario Handling

Handling deletion failures:

// Check for active connections
db.currentOp().inprog.forEach(op => {
  if(op.ns.startsWith("targetDB.")) {
    printjson(op)
  }
})

// Force deletion (requires admin permissions)
use admin
db.runCommand({
  killOp: 12345 // Operation ID
})

Best practices for creating temporary databases:

function createTempDB(dbName, ttlHours) {
  use admin
  db.runCommand({
    create: dbName,
    temp: true,
    expireAfterSeconds: ttlHours * 3600
  })
  
  // Set up automatic cleanup
  db.adminCommand({
    setParameter: 1,
    temporaryDatabaseExpiryTime: ttlHours * 3600
  })
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.