3

I'm fetching a document using db.coll.findOne. I wanted to get size of the document in bytes using nodejs with only mongo-native driver.can it be possible?

1 Answers1

5

It is possible using BSON (it's a dependency of the mongodb driver):

var bson = require("bson");
var BSON = new bson.BSONPure.BSON();

db.coll.findOne(query).then(function(err, doc) {
  var size = BSON.calculateObjectSize(doc);
});
Shanoor
  • 13,344
  • 2
  • 29
  • 40
  • i was able to get size values.but it differs from "Object.bsonsize" value is there any reason for the difference in size? – Narayansingh Rajput Jan 14 '16 at 01:44
  • 1
    I don't know why exactly but a guess: `Object.bsonsize()` returns the true size of the stored document, `calculateObjectSize()` will only try to calculate it (the name is a good indicator :p) so anything thing can lead to a different calculated size. – Shanoor Jan 14 '16 at 16:50
  • 2
    I had to change it to `new bson.BSON()` to get it working. I guess the api changed since 2013. – Mr. Goferito Mar 11 '19 at 18:48