阿里云主机折上折
  • 微信号
Current Site:Index > The deletion of documents (deleteOne, deleteMany)

The deletion of documents (deleteOne, deleteMany)

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

Document Deletion (deleteOne, deleteMany)

MongoDB provides two primary methods for document deletion: deleteOne and deleteMany. These methods are used to delete a single document and multiple documents, respectively, and are commonly used functionalities in database operations.

The deleteOne Method

The deleteOne method is used to delete the first document that matches the specified condition in a collection. If multiple documents match the condition, only the first matching document will be deleted.

// Example: Delete the first document with the name "张三" in the users collection
const result = await db.collection('users').deleteOne({ name: "张三" });
console.log(result.deletedCount); // Output the number of deleted documents

The deleteOne method returns a Promise that resolves to an object containing the following properties:

  • deletedCount: The number of documents deleted (0 or 1)
  • acknowledged: Whether the operation was acknowledged (boolean)

The deleteMany Method

The deleteMany method is used to delete all documents that match the specified condition in a collection.

// Example: Delete all documents in the users collection where age is greater than 30
const result = await db.collection('users').deleteMany({ age: { $gt: 30 } });
console.log(result.deletedCount); // Output the total number of deleted documents

The structure of the object returned by deleteMany is similar to that of deleteOne, but deletedCount may be greater than 1.

Using Deletion Conditions

The syntax for deletion conditions is the same as for query operations, and various query operators can be used:

// Using comparison operators
await db.collection('products').deleteMany({ price: { $lt: 100 } });

// Using logical operators
await db.collection('users').deleteMany({ 
  $or: [
    { status: "inactive" },
    { lastLogin: { $lt: new Date(Date.now() - 30*24*60*60*1000) } }
  ]
});

// Using array operators
await db.collection('articles').deleteMany({ tags: { $in: ["obsolete", "deprecated"] } });

Considerations for Deletion Operations

  1. Atomicity: Deletion operations in MongoDB are atomic at the single-document level. For deletions involving multiple documents, each document deletion is atomic, but the entire operation is not.

  2. Performance Impact: Deleting a large number of documents may affect database performance, especially in production environments.

  3. Index Usage: Deletion operations utilize indexes to improve performance but also incur index maintenance overhead.

  4. Storage Space: Deleting documents does not automatically free up disk space. Commands like compact or repairDatabase must be used to reclaim space.

Alternatives to Deletion Operations

In some cases, you may not want to physically delete documents but instead use a "soft delete" approach:

// Soft delete example: Add a deleted field to mark documents as deleted
await db.collection('orders').updateMany(
  { status: "cancelled" },
  { $set: { deleted: true, deletedAt: new Date() } }
);

This approach allows for data recovery while maintaining referential integrity.

Deletion Operations and Transactions

In MongoDB 4.0+, deletion operations can be included in transactions:

const session = db.client.startSession();
try {
  await session.withTransaction(async () => {
    await db.collection('users').deleteOne({ _id: userId }, { session });
    await db.collection('profiles').deleteOne({ userId }, { session });
  });
} finally {
  session.endSession();
}

Error Handling for Deletion Operations

Deletion operations may fail for various reasons, and errors should be handled appropriately:

try {
  const result = await db.collection('logs').deleteMany({ createdAt: { $lt: cutoffDate } });
  if (result.deletedCount === 0) {
    console.log('No matching documents found');
  }
} catch (error) {
  console.error('Deletion operation failed:', error);
}

Monitoring Deletion Operations

Deletion operations can be tracked using MongoDB's monitoring tools:

// Get statistics for deletion operations
const stats = await db.command({ collStats: "users" });
console.log('Number of deletion operations:', stats.deleted);

Permission Control for Deletion Operations

MongoDB provides fine-grained permission control to restrict deletion operations:

// Create a role that can only delete documents matching specific conditions
db.createRole({
  role: "limitedDeleteRole",
  privileges: [{
    resource: { db: "mydb", collection: "orders" },
    actions: ["delete"],
    conditions: [{ "q.$.status": { $eq: "cancelled" } }]
  }],
  roles: []
});

Performance Optimization for Deletion Operations

For large-scale deletion operations, consider the following optimization strategies:

  1. Batch deletion:
const batchSize = 1000;
let deletedCount = 0;
do {
  const result = await db.collection('tempData').deleteMany({}, { limit: batchSize });
  deletedCount = result.deletedCount;
  console.log(`Deleted ${deletedCount} documents`);
} while (deletedCount > 0);
  1. Perform large-scale deletions during off-peak hours

  2. Temporarily disable indexes before deletion

Deletion Operations and Replica Sets

In a replica set environment, deletion operations are propagated to all replica nodes. Write concern can be configured to control the acknowledgment level:

// Wait for the deletion operation to propagate to the majority of nodes
await db.collection('auditLogs').deleteMany(
  { retentionDate: { $lt: new Date() } },
  { writeConcern: { w: "majority" } }
);

Deletion Operations and Sharded Clusters

In a sharded cluster, deletion operations are routed to the shards containing the target documents:

// Delete a document in a sharded collection
await db.collection('shardedData').deleteOne({ _id: shardKeyValue });

For cross-shard deletion operations, mongos coordinates the operations across the shards.

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

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