QA
Intermediate LevelMongoDB & Mongoose

How does the compact command defragment WiredTiger collection disk storage?

❓ Interview Prompt: Explain WiredTiger collection fragmentation, unallocated free storage space, compact command, and reclaiming disk space.

Deleting millions of MongoDB documents leaves unallocated fragmented gaps inside WiredTiger collection data files. The filesystem 'storageSize' remains high even though 'dataSize' drops!

The compact Command:

Running 'db.runCommand({ compact: "collection_name" })' rewrites collection storage files, defragmenting data and releasing unused disk space back to the OS.

Code Implementation Example

typescript
import mongoose from 'mongoose';

async function compactCollection(collectionName: string) {
  const db = mongoose.connection.db;
  // Defragment collection storage files
  await db!.command({ compact: collectionName });
}
💡Executing the compact command to defragment collection disk storage.
🎯 Interview Key Takeaway

Run the compact command to reclaim fragmented disk space after deleting large volumes of collection documents.

#compact#WiredTiger#Defragmentation#Intermediate
Back to all MongoDB & Mongoose Questions→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?