Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
    client.send(doc);
  });                
});
like image 617
Mads Mogenshøj Avatar asked Apr 26 '11 10:04

Mads Mogenshøj


2 Answers

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.

like image 67
Andrew Orsich Avatar answered Nov 05 '22 23:11

Andrew Orsich


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.

like image 21
Ram Dwivedi Avatar answered Nov 05 '22 23:11

Ram Dwivedi