ericsoco
ericsoco

Reputation: 26253

How to count documents returned by Node-MongoDB-native stream()?

When I stream() documents in the NodeJS MongoDB native driver, how do I determine the total number of documents that will be returned? Useful for reporting query progress, for example.

var stream = collection.find(query, fields, options).stream()
    .on("data", onData)
    .on("end", onEnd)
    .on("error", onError);

Upvotes: 0

Views: 1072

Answers (1)

Morgan ARR Allen
Morgan ARR Allen

Reputation: 10678

You can try calling collection.count first.

collection.count(function(err, total) {
  var count = 0;
  var progress = 0;
  function onData() {
    progress = (++count / total) * 100;
  }

  var stream = collection.find(query, fields, options).stream()
    .on("data", onData)
    .on("end", onEnd)
    .on("error", onError);
});

Upvotes: 1

Related Questions