MongoDB Collection Stats



MongoDB Collection Stats

In MongoDB, the stats operation is used to retrieve statistics about a collection. This method is essential for monitoring and analyzing the performance and storage characteristics of MongoDB collections.


Syntax

db.collection.stats(options)

The stats method takes an optional options parameter to customize the retrieval of statistics.


Example MongoDB Collection Stats

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

1. Retrieve Collection Statistics

db.programGuru.stats()

This command retrieves statistics about 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 collection statistics.

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 Stats

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 Stats

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 Stats

Step 4: Retrieve Collection Statistics

This step involves using the stats method to retrieve statistics about the programGuru collection.

db.programGuru.stats()

We retrieve statistics about the programGuru collection.

MongoDB Collection Stats

Conclusion

The MongoDB stats operation is crucial for monitoring and analyzing the performance and storage characteristics of collections. Understanding how to use this method allows you to efficiently manage and optimize your MongoDB collections.