从MongoDB find()结果集中识别最后一个文档 [英] Identify last document from MongoDB find() result set
问题描述
我正在尝试使用websocket将数据从node.js/MongoDB实例流式传输"到客户端.一切都很好.
I'm trying to 'stream' data from a node.js/MongoDB instance to the client using websockets. It is all working well.
但是如何确定结果中的最后一个文档?我正在使用 node-mongodb-native 从node.js连接到MongoDB.
But how to I identify the last document in the result? I'm using node-mongodb-native to connect to MongoDB from node.js.
一个简化的示例:
collection.find({}, {}, function(err, cursor) {
if (err) sys.puts(err.message);
cursor.each(function(err, doc) {
client.send(doc);
});
});
推荐答案
由于mongodb objectId包含创建日期,因此您可以按id排序,然后降序使用limit(1):
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);
注意:我一点都不熟悉node.js,上面的命令是mongo shell命令,我想您可以轻松地将其重写为node.js.
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.
这篇关于从MongoDB find()结果集中识别最后一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!