MongoDB Collection Storage Size



MongoDB Collection Storage Size

In MongoDB, the storageSize operation is used to retrieve the total storage size allocated to a collection. This method is essential for understanding the storage utilization and capacity planning within MongoDB collections.


Syntax

db.collection.storageSize()

The storageSize method does not take any parameters and returns the total storage size in bytes allocated to the specified collection.


Example MongoDB Collection Storage Size

Let's look at an example of how to use the storageSize method in the programGuru collection in MongoDB:

1. Retrieve Collection Storage Size

db.programGuru.storageSize()

This command retrieves the total storage size allocated to the programGuru collection.


Full Example

Let's go through a complete example that includes switching to a database, creating a collection, inserting documents, and retrieving the storage size of the collection.

Step 1: Switch to a Database

This step involves switching to a database named myDatabase.

use myDatabase

In this example, we switch to the myDatabase database.

MongoDB Collection Storage Size

Step 2: Create a Collection

This step involves creating a new collection named programGuru in the myDatabase database.

db.createCollection("programGuru")

Here, we create a collection named programGuru.

MongoDB Collection Storage Size

Step 3: Insert Documents into the Collection

This step involves inserting documents into the programGuru collection.

db.programGuru.insertMany([
    { name: "John Doe", age: 30, email: "john.doe@example.com" },
    { name: "Jane Smith", age: 25, email: "jane.smith@example.com" },
    { name: "Jim Brown", age: 35, email: "jim.brown@example.com" }
])

We insert multiple documents into the programGuru collection.

MongoDB Collection Storage Size

Step 4: Retrieve Collection Storage Size

This step involves using the storageSize method to retrieve the total storage size allocated to the programGuru collection.

db.programGuru.storageSize()

We retrieve the total storage size allocated to the programGuru collection.

MongoDB Collection Storage Size

Conclusion

The MongoDB storageSize operation is crucial for understanding the storage utilization and capacity planning within collections. Understanding how to use this method allows you to efficiently manage and optimize the storage of your MongoDB collections.