How can I get size (bytes) of a MongoDB collection with Mongoose?
Asked Answered
T

3

6

Imagine I have a Mongoose model like this:

mongoose = require('mongoose')
Products = mongoose.model('Products')

How do I get size of the full corresponding collection in bytes? I found db.collection.storageSize, but it's nowhere to be found in the Mongoose API docs.

Timotheus answered 2/5, 2016 at 13:35 Comment(0)
I
8

Mongoose doesn't provide an abstraction for this, but you can access the native driver collection methods like stats() from the collection property of a Mongoose Model. That method provides the collection's size as the storageSize property of the results:

Products.collection.stats(function(err, results) {
    console.log(results.storageSize);
});
Intelligence answered 2/5, 2016 at 14:14 Comment(3)
what if I wanted to check the size of whole database, the situation is I have 500mb of free MongoDB hosting and I wanted to display on admin panel how much database is remaining and also genrate emails when reaching 90% to avoid any inconvenience because of database full, the answer could be "get all sizes of all collections one by one and then add" I understand but it would be more convenient if there is a way to get size of whole database at once, any help would be appriciatedCaseinogen
Best to post that as a new question @InzamamMalikIntelligence
const stats = await mongoose.connection.db.stats()Demission
M
0
var stats = Products.stats(function(err, stats) {
  // second parameter stats contains the result from  stats
  var storageSize = stats.storageSize;
});

gets statistics for Products collection.

Mansfield answered 2/5, 2016 at 13:44 Comment(2)
Where did you get the db object using Mongoose?Timotheus
Sorry, using Mongoose model you should be able to just use it... See my updated answerMansfield
V
0

When I tried to use .stats() to get the storage size, the lib shows that the method stats() has been deprecated. The pipeline $collstats in aggregation is the correct way to acquire the data size in bytes.

enter image description here

https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/

db.collection.aggrate([{
 {
  $collStats:
    {
      // Kb=>scale=1024,...
      storageStats: { scale: <number> }, 
    }
 }
}])

enter image description here

The output will contain the storageStats like this

enter image description here

Vicariate answered 20/2 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.