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) {
4/26/2011 10:28:42 AM

Accepted Answer

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.

4/26/2011 11:52:26 AM

Say I have companies collection. Below snippet gives me last document in the collection.


Code cannot rely on _id as it may not be on a specific pattern always if it's a user defined value.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow