MongoDB Data Size


MongoDB Data Size

In MongoDB, the dataSize operation is used to return the size of the data stored in a collection. This method is essential for monitoring and managing storage utilization within MongoDB collections.


Syntax

db.collection.dataSize()

The dataSize method does not take any parameters and returns the size of the data in bytes.


Example MongoDB Data Size

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

1. Get Data Size

db.programGuru.dataSize()

This command returns the size of the data stored in 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 data size.

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 Data 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 Data 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 Data Size

Step 4: Get Data Size of the Collection

This step involves using the dataSize method to retrieve the size of the data stored in the programGuru collection.

db.programGuru.dataSize()

We retrieve the size of the data stored in the programGuru collection.

MongoDB Data Size

Conclusion

The MongoDB dataSize operation is crucial for monitoring and managing storage utilization. Understanding how to use this method allows you to efficiently manage the storage needs of your MongoDB collections.