Sling Academy
Home/MongoDB/MongoDB: How to determine the size of a database (5 ways)

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

Last updated: February 01, 2024

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.

Next Article: MongoDB: How to create an admin user and enable authentication

Previous Article: 4 Ways to Drop a Database in MongoDB

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)