Mads Mogenshøj Mads Mogenshøj - 8 months ago 70
Node.js Question

Identify last document from MongoDB find() result set

I'm trying to 'stream' data from a node.js/MongoDB instance to the client using websockets. It is all working well.

But how to I identify the last document in the result? I'm using node-mongodb-native to connect to MongoDB from node.js.

A simplified example:

collection.find({}, {}, function(err, cursor) {
if (err) sys.puts(err.message);

cursor.each(function(err, doc) {

Answer Source

Since mongodb objectId contatins creation date you can sort by id, descending and then use limit(1):

db.collection.find().sort( { _id : -1 } ).limit(1);

Note: i am not familiar with node.js at all, above command is mongo shell command and i suppose you can easy rewrite it to node.js.