Skip to content
Studio 3T - The professional GUI, IDE and client for MongoDB
  • Tools
    • Aggregation Editor
    • IntelliShell
    • Visual Query Builder
    • Export Wizard
    • Import Wizard
    • Query Code
    • SQL Query
    • Connect
    • Schema Explorer
    • Compare
    • SQL ⇔ MongoDB Migration
    • Data Masking
    • Task Scheduler
    • Reschema
    • More Tools and Features
  • Solutions
  • Resources
    • Knowledge Base
    • MongoDB Tutorials & Courses
    • Tool/Feature Documentation
    • Blog
    • Community
    • Testimonials
    • Whitepapers
    • Reports
  • Contact us
    • Contact
    • Sales Support
    • Feedback and Support
    • Careers
    • About Us
  • Store
    • Buy Now
    • Preferred Resellers
    • Team Pricing
  • Download
  • My 3T
search

How to get MongoDB statistics for all collections? #Studio3T_AMA

Posted on: 06/07/2022 by Dj Walker-Morgan

Q: I want to get the MongoDB statistics for all my MongoDB collections in Studio 3T. How?

Welcome to the latest Studio 3T Ask Manatees Anything – #Studio3T_AMA. Want to know how to use Studio 3T to make your MongoDB life better? Just tweet and use #Studio3T_AMA or email [email protected].

A: This question came from 3T Community user Hannes Schurig, who wondered if there was a way to report on the MongoDB collection statistics that appear when hovering over a collections name in the Studio 3T Connection Tree. Well, right now, there isn’t a built in tool for that, but Studio 3T makes it easy to create and run a Mongo script to do that. So let’s do that, and show you some pro-tips for scripting.

Without further ado, here is the script.

var dbs = db.getMongo().getDBNames();

for (adb of dbs) {
    var colls = db.getSiblingDB(adb).getCollectionNames()

    for (coll of colls) {
        var info = db.getSiblingDB(adb).getCollection(coll).stats(1024);
        if (info.ok) {
            printjson({
                ns: info.ns,
                count: info.count,
                size: info.size,
                storageSize: info.storageSize,
                nindexes: info.nindexes,
                totalIndexSize: info.totalIndexSize
            });
        }
    }
}

Running the MongoDB Statistics Script

Connect to a MongoDB database in Studio 3T. Then, open IntelliShell for any server, database or collection in that server.Next, paste in that script and click the Run button.

Statistics table as results for running the articles script.

The columns mostly match up with the fields you see when you hover over a collection and the tool-tip pops up. 

Hovering for MongoDB Statistics on a collection

If you’d run this script in the raw shell, your results would have appeared as just JSON. Thanks to Studio 3T, they are formatted as a table (or JSON). And you can sort the columns to quickly find the collection with the most records (count), or largest storage or biggest indexes.

By default, the results are limited to 50 collections. Go to the Preferences/General and adjust Initial Page Size when Showing Documents to increase the number of collections initially shown.

BTS: Behind the Script

Very simply. The script first gets all the names of the databases in the server using getDBNames() as an array. Then it uses a for loop to step through each database name in the array. 

For each named database, it gets all the collection names using getCollectionNames() as an array. And then it uses a for loop to step through each collection name in the array.

For each collection, it then runs the stats() method which returns a typically very large document full of information about the collection. The number passed to the stats method is the scaling value for storage sizes. By default, values are returned in bytes. Pass 1024 (1K) to stats and the values are scaled in Kilobytes.

 It may, though, actually return a document with an explanation of whether there was an error getting the stats. This happens more than you would suspect, because getCollectionNames() returns collection AND view names and view names don’t have any statistics because they are calculated on demand from an aggregation pipeline. 

How can we tell if there’s an error? Well, there’s an “ok” field in the returned document. If that’s set to true, we print out our statistics. We only want some of the statistics, so we use the printjson command and pass it a javascript object with named fields and values from the statistics document. 

Why don’t we just print the values? Well, this is where IntelliShell comes in. If it sees JSON data being output in the shell, it turns it into a table (or JSON) display, using the field names as column names. This makes it easy to view and compare and sort the returned data without  adding more script.

Finally

Don’t forget to use Studio 3T’s bookmarks to save this script ready for when you next need to get your MongoDB statistics. As you can see, while scripting with MongoDB is powerful, using Studio 3T makes it so much easier to read and use the results from your scripts.


How helpful was this article?
This article was hideous
This article was bad
This article was ok
This article was good
This article was great
Thank you for your feedback!

About The Author

Dj Walker-Morgan

Dj has been around since Commodore had Pets and Apples grew everywhere. With a background in Unix and development, he's been around the technology business writing code or writing content ever since.

Related articles

  • I don’t get unwind in aggregation – why do I need it?
  • How do you make Studio 3T export MongoDB collections to unique files? #Studio3T_AMA
  • What’s New in Studio 3T 2021.2 | Task Scheduler Now Available for All
  • A roundup of Studio 3T in 2021: All the best bits
  • Pitching For All At The 3T Pitch Day

Tags

2022 academy aggregation AMA atlas Certification christmas community connections culture date tags events export features hackolade import intellishell In Use JSON knowledge base migration modelling mongodb mongoodb mongosh My 3T productivity query regex releases schema security SQL Studio 3T tasks time series tips updates webinar windows

Browse by MongoDB topic

  • Connecting to MongoDB
  • Database Administration & Security
  • Getting Started with MongoDB
  • Getting Started with Studio 3T
  • Import/Export
  • Job Automation & Scheduling
  • MongoDB Aggregation Framework
  • MongoDB/Studio 3T Workshops
  • Performance
  • Query & CRUD Operations
  • Reference
  • Schema
  • Studio 3T Licensing
  • Support and other resources
  • Working with MongoDB & SQL
  • Working with MongoDB Atlas

Studio 3T

MongoDB Enterprise Certified Technology PartnerSince 2014, 3T has been helping thousands of MongoDB developers and administrators with their everyday jobs by providing the finest MongoDB tools on the market. We guarantee the best compatibility with current and legacy releases of MongoDB, continue to deliver new features with every new software release, and provide high quality support.

Find us on FacebookFind us on TwitterFind us on YouTubeFind us on LinkedIn

Education

  • Free MongoDB Tutorials
  • Connect to MongoDB
  • Connect to MongoDB Atlas
  • Import Data to MongoDB
  • Export MongoDB Data
  • Build Aggregation Queries
  • Query MongoDB with SQL
  • Migrate from SQL to MongoDB

Resources

  • Feedback and Support
  • Sales Support
  • Knowledge Base
  • FAQ
  • Reports
  • White Papers
  • Testimonials
  • Discounts

Company

  • About Us
  • Blog
  • Careers
  • Legal
  • Press
  • Privacy Policy
  • EULA

© 2023 3T Software Labs Ltd. All rights reserved.

  • Privacy Policy
  • Cookie settings
  • Impressum

We value your privacy

With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data.

By clicking “Accept all”, you consent to the storage of cookies and the processing of personal data for these purposes, including any transfers to third countries. By clicking on “Decline all”, you do not give your consent and we will only store cookies that are necessary for our website. You can customize the cookies we store on your device or change your selection at any time - thus also revoking your consent with effect for the future - under “Manage Cookies”, or “Cookie Settings” at the bottom of the page. You can find further information in our Privacy Policy.
Accept all
Decline all
Manage cookies
✕

Privacy Preference Center

With your consent, we and third-party providers use cookies and similar technologies on our website to analyse your use of our site for market research or advertising purposes ("analytics and marketing") and to provide you with additional functions (“functional”). This may result in the creation of pseudonymous usage profiles and the transfer of personal data to third countries, including the USA, which may have no adequate level of protection for the processing of personal data. Please choose for which purposes you wish to give us your consent and store your preferences by clicking on “Accept selected”. You can find further information in our Privacy Policy.

Accept all cookies

Manage consent preferences

Essential cookies are strictly necessary to provide an online service such as our website or a service on our website which you have requested. The website or service will not work without them.

Performance cookies allow us to collect information such as number of visits and sources of traffic. This information is used in aggregate form to help us understand how our websites are being used, allowing us to improve both our website’s performance and your experience.

Google Analytics

Google Ads

Bing Ads

Facebook

LinkedIn

Quora

Hotjar

Reddit

Functional cookies collect information about your preferences and choices and make using the website a lot easier and more relevant. Without these cookies, some of the site functionality may not work as intended.

HubSpot

Social media cookies are cookies used to share user behaviour information with a third-party social media platform. They may consequently effect how social media sites present you with information in the future.

Accept selected