Introduction to MongoDB collection.totalSize() Method

totalSize() is a method in MongoDB that can be used to get the total size of a collection.

Syntax

The syntax of the totalSize() method is as follows:

db.collection.totalSize()

Where db.collection represents the collection to get information from.

Use Cases

The totalSize() method is usually used to get the total size of a collection. This method can help you understand the amount of space that the collection occupies on disk, in order to optimize and tune it.

Example

Here is an example of using the totalSize() method to get the total size of a collection.

Assuming we have a collection named products that contains the following 4 documents:

{ "_id": 1, "name": "Product 1", "price": 10 }
{ "_id": 2, "name": "Product 2", "price": 20 }
{ "_id": 3, "name": "Product 3", "price": 30 }
{ "_id": 4, "name": "Product 4", "price": 40 }

We can use the following code to get the total size of the products collection:

db.products.totalSize()

After running the above code, the following result will be returned:

16384

Conclusion

The totalSize() method is a method in MongoDB that can be used to get the total size of a collection. When using this method, you only need to specify the collection to get the information from. After executing this method, the amount of space the collection occupies on disk will be returned.