在 MongoDB 中查询 createTime 最新的一个文档,可以使用以下方法:

方法 1:使用 sort() 和 limit()

db.collection.find()
  .sort({ createTime: -1 })
  .limit(1)

这个查询会按照 createTime 降序排列(-1 表示降序),然后只返回第一条记录。

方法 2:使用 findOne() 和 sort()

db.collection.findOne(
  {},
  { sort: { createTime: -1 } }
)

这个方法直接返回一个文档对象,而不是游标。

方法 3:使用聚合管道

db.collection.aggregate([
  { $sort: { createTime: -1 } },
  { $limit: 1 }
])

聚合管道提供了更强大的数据处理能力,适合复杂查询。

注意事项