按 mdate 字段对集合进行排序并获得 MongoDB 中的最新 20 个结果 (LIMIT)?

Sort collection by mdate field and get the latest 20 results (LIMIT) in MongoDB?

我有一个名为 messages 的集合,我需要按 mdate 排序并仅获取 SQL 中 LIMIT 的最新 20 个结果,怎么样?我正在玩这个但没有成功:

db.getCollection('messages').find({}, {"sort" : ['mdate', 'asc']} );

如果您想要最后 20 个文档,您应该 $sort your document in descending order and use the $limit 运算符 return 只有 20 个文档。

db.messages.find().sort({ 'mdate': -1 }).limit(20)