Skip to content

Instantly share code, notes, and snippets.

@nicokaiser
Created October 11, 2011 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicokaiser/1279333 to your computer and use it in GitHub Desktop.
Save nicokaiser/1279333 to your computer and use it in GitHub Desktop.
var mongodb = require('mongodb');
// This example selects all documents of a collection and checks if they should be displayed.
// 15 documents should be displayed, but I have to select all from the DB because maybe
// myCheckFunction returns true only for the last 15 elements selected (if any).
// So at some point (if I have seen enough documents) the DB can stop sending me documents,
// i.e. not fetch another batch of 30 documents in this case.
var db = new mongodb.Db('mydb', new mongodb.Server('localhost', 27017, {}));
db.open(function(err, db) {
db.collection('mycollection', function(err, collection) {
var count = 0;
var stream = collection.find({}).streamRecords({fetchSize: 30});
stream.on('end', function() {
db.close();
});
stream.on('data', function(data) {
// "myCheckFunction" checks if this document should be displayed or not
// this may be something I cannot do in MongoDB.
if (myCheckFunction(data)) {
count++;
doDisplay(data); // ...
if (count > 15) { // seen enough
stream.destroy(); // not implemented!
}
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment