Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the disk space (bytes) used by the documents returned from a mongoose query?

The scenario is as follows:

  • using Mongoose.js in Node.js
  • perform a query, like Model.find().where('something', 'value').exec(callback)
  • you receive an array of documents in the callback

How can I determine the size of those documents on disk?

Approximations are OK, for me at least.

like image 379
ruffrey Avatar asked Jan 16 '15 14:01

ruffrey


People also ask

What does find in Mongoose return?

find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries. You don't instantiate a Query directly, Customer.

What is document size in MongoDB?

The maximum BSON document size is 16 megabytes. The maximum document size helps ensure that a single document cannot use excessive amount of RAM or, during transmission, excessive amount of bandwidth. To store documents larger than the maximum size, MongoDB provides the GridFS API.

How do you count in mongoose?

Mongoose count() Function This functions basically specifies this query as a count query. Parameters: This function accepts one array parameter i.e. callback function. Return Value: This function returns Query Object.

What is a mongoose callback?

All callbacks in Mongoose use the pattern: callback(error, result) . If an error occurs executing the query, the error parameter will contain an error document, and result will be null. If the query is successful, the error parameter will be null, and the result will be populated with the results of the query.


1 Answers

You can do this by executing your query as a lean query (to get plain JavaScript objects instead of Mongoose document instances) and then dipping down into the BSON library that's part of the native MongoDB driver and calling calculateObjectSize:

var bson = mongoose.mongo.BSON;

Model.find().where('something', 'value').lean().exec(function(err, docs) {
    var docsBsonSize = bson.calculateObjectSize(docs));
});

It won't give you the size on disk, but it should be a good approximation of the size of BSON docs.

like image 199
JohnnyHK Avatar answered Oct 27 '22 20:10

JohnnyHK