简体   繁体   中英

Nodejs mongodb fetching document size without actually fetching cursor

My question is, how can I get a cursor size (in KBs) without actually fetching it ?

I've already examined a lot of question such as here But I don't want to fetch query result to learn how much KB is it.

I just want something like:

var MongoClient = require('mongodb').MongoClient,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  var collection = db.collection('simple_query');

  // Insert a bunch of documents for the testing
  collection.insertMany([{a:1}, {a:2}, {a:3}], {w:1}, function(err, result) {
    test.equal(null, err);

    collection.find(/**SOME QUERY*/).size(function(err, SIZE) {
      test.equal(null, err);
      test.equal(32111351, SIZE); // in bytes or kilobytes whatever
      db.close();
    });
  });
});

Something like this?

var avgSize = db.collectionName.stats().avgObjSize;

// ...

collection.count(/* some query */, function(err, count) {
    var approximateSize = count*avgSize; // This could work for simple database models
}

I know its not perfect, but it is the best way i found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM