In MongoDB, the totalSize
operation is used to retrieve the total size of a collection, including the size of all documents and indexes. This method is essential for understanding the storage utilization and capacity planning within MongoDB collections.
db.collection.totalSize()
The totalSize
method does not take any parameters and returns the total size in bytes of the specified collection, including both documents and indexes.
Let's look at an example of how to use the totalSize
method in the programGuru
collection in MongoDB:
db.programGuru.totalSize()
This command retrieves the total size of the programGuru
collection, including the size of all documents and indexes.
Let's go through a complete example that includes switching to a database, creating a collection, creating indexes, and retrieving the total size of the collection.
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
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.
This step involves creating multiple indexes in the programGuru
collection.
db.programGuru.createIndexes([
{ key: { name: 1 }, name: "name_index" },
{ key: { age: -1 }, name: "age_index" },
{ key: { email: 1 }, name: "email_index", unique: true }
])
We create three indexes: an ascending index on the name
field, a descending index on the age
field, and a unique index on the email
field.
This step involves using the totalSize
method to retrieve the total size of the programGuru
collection, including both documents and indexes.
db.programGuru.totalSize()
We retrieve the total size of the programGuru
collection.
The MongoDB totalSize
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.