Identify last document from MongoDB find() result set

后端 未结 3 1168
野性不改
野性不改 2020-12-29 07:27

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 t

相关标签:
3条回答
  • 2020-12-29 07:46

    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.

    0 讨论(0)
  • 2020-12-29 08:04

    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
       ....
    }); 
    
    0 讨论(0)
  • 2020-12-29 08:06

    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.

    0 讨论(0)
提交回复
热议问题