在 MongoDB 中查询 createTime 最新的一个文档,可以使用以下方法:
db.collection.find()
.sort({ createTime: -1 })
.limit(1)
这个查询会按照 createTime 降序排列(-1 表示降序),然后只返回第一条记录。
db.collection.findOne(
{},
{ sort: { createTime: -1 } }
)
这个方法直接返回一个文档对象,而不是游标。
db.collection.aggregate([
{ $sort: { createTime: -1 } },
{ $limit: 1 }
])
聚合管道提供了更强大的数据处理能力,适合复杂查询。
索引优化: 为了提高查询性能,建议在 createTime 字段上创建索引:
db.collection.createIndex({ createTime: -1 })
字段类型: 确保 createTime 字段存储的是 Date 类型或可比较的时间戳格式
性能考虑: 如果集合数据量很大,使用索引可以显著提高查询速度