MongoDB: How to determine the size of a database (5 ways)

Updated: February 1, 2024 By: Guest Contributor Post a comment

Introduction

Knowing the size of a MongoDB database is crucial for monitoring storage resources, planning capacity, and optimizing performance. This guide will provide various methods to determine the size of a MongoDB database, ranging from basic to advanced techniques, accompanied by code examples and their expected outputs.

Using the `db.stats()` Method

The simplest way to find out the size of your MongoDB database is by using the db.stats() method. This function returns a document containing various statistics about the database. Here’s an example of how to use it:

use yourDatabaseName
var stats = db.stats()
print("Database Size: " + (stats.dataSize / (1024 * 1024 * 1024)).toFixed(2) + " GB");
print("Storage Size: " + (stats.storageSize / (1024 * 1024 * 1024)).toFixed(2) + " GB");

Output:

Database Size: 1.75 GB
Storage Size: 2.00 GB

The dataSize field represents the total size of all the documents in the database, while the storageSize field shows the total amount of space allocated to collections for document storage.

Using the `show dbs` Command

If you have access to the MongoDB shell, you can use the show dbs command to list all databases along with their sizes. It’s a quick way to get an overview of database sizes without writing any code:

show dbs

Output:

admin  0.000GB
default_db  0.002GB
yourDatabaseName  1.750GB

Keep in mind that sizes are displayed in gigabytes, and the values are rounded.

Estimating the Database Size with `collStats`

For a more detailed analysis of individual collection sizes within a database, MongoDB provides the db.collection.stats() or db.runCommand({ collStats: }). These commands return statistics about collection size, index size, and other relevant information. Here’s a code snippet that sums up the sizes of all collections in a database:

use yourDatabaseName
var collections = db.getCollectionNames();
var totalSize = 0;
var totalIndexSize = 0;
collections.forEach(function(collectionName) {
    var stats = db[collectionName].stats();
    totalSize += stats.size;
    totalIndexSize += stats.totalIndexSize;
});
print("Total Collections Size: " + (totalSize / (1024 * 1024 * 1024)).toFixed(2) + " GB");
print("Total Index Size: " + (totalIndexSize / (1024 * 1024 * 1024)).toFixed(2) + " GB");

Output:

Total Collections Size: 1.50 GB
Total Index Size: 0.25 GB

This is helpful for understanding how much space each collection and its indexes are taking up within your database.

Using MongoDB’s Aggregation Framework

For an even deeper dive into your data, MongoDB’s aggregation framework can be employed to calculate the size of documents. You can aggregate data across one or multiple collections and get the size of specific subsets of your data:

use yourDatabaseName
db.getCollectionNames().forEach(function(collectionName) {
    var results = db[collectionName].aggregate([
        { $group: {
            _id: null,
            totalSize: { $sum: { $bsonSize: "$" } }
        }}
    ]);
    if (results.hasNext()) {
        var res = results.next();
        print(collectionName + " - Size: " + (res.totalSize / (1024 * 1024)).toFixed(2) + " MB");
    }
});

Output:

collectionOne - Size: 500.00 MB
collectionTwo - Size: 750.00 MB
collectionThree - Size: 505.42 MB

This script will calculate the size of each document in the collection and then sum it to give the total size of the stored documents in each collection.

Advanced: Interacting with the MongoDB Driver

For applications that interface directly with MongoDB through a programming language’s driver, you can call database commands programmatically. Here’s an example using the Node.js MongoDB driver:

const MongoClient = require('mongodb').MongoClient;
const uri = "";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

client.connect(err => {
  const db = client.db("yourDatabaseName");

  db.command({ dbStats: 1 }).then(stats => {
    console.log(`Database Size: ${(stats.dataSize / (1024 * 1024 * 1024)).toFixed(2)} GB`);
    console.log(`Storage Size: ${(stats.storageSize / (1024 * 1024 * 1024)).toFixed(2)} GB`);
    client.close();
  });
});

Output:

{
    "Database Size": "1.75 GB",
    "Storage Size": "2.00 GB"
}

This approach is better suited for automated processes or applications that already interact with MongoDB and need to perform regular size checks.

Conclusion

There are several ways to determine the size of a MongoDB database, each offering different levels of detail and use cases. By combining these methods, you can efficiently monitor your database’s footprint and make informed decisions regarding data management and scaling requirements.