Mads Mogenshøj
Mads Mogenshøj

Reputation: 2068

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);
  });                
});

Upvotes: 18

Views: 17778

Answers (3)

Ram Dwivedi
Ram Dwivedi

Reputation: 470

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.

Upvotes: 1

Daphoque
Daphoque

Reputation: 4678

Use sort and limit, if you want to use cursor :

var last = null;
var findCursor = collection.find({}).cursor();
findCursor.on("data", function(data) {
   last = data;
   ...
});
findCursor.on("end", function(data) {
   // last result in last
   ....
}); 

Upvotes: 0

Andrew Orsich
Andrew Orsich

Reputation: 53705

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.

Upvotes: 31

Related Questions