Identify last document from MongoDB find() result set


Question

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) {
    client.send(doc);
  });                
});
1
17
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.

29
4/26/2011 11:52:26 AM

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

db.companies.find({},{"_id":1}).skip(db.companies.find().count()-1);

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
Icon