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?
Asked
Active
Viewed 3,084 times
3
-
1Maybe http://stackoverflow.com/questions/22008822/mongo-get-size-of-single-document ? – Shanoor Jan 13 '16 at 13:03
-
1"Object.bsonsize" execute only in mongoshell i need to get size of document in node.js application – Narayansingh Rajput Jan 13 '16 at 13:28
1 Answers
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
-
1I 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
-
2I 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