Python中使用pymongo如何按插入顺序倒序排序
null
Python中使用pymongo如何按插入顺序倒序排序
1 回复
from pymongo import MongoClient, DESCENDING
# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database']
collection = db['your_collection']
# 方法1:使用_id字段(ObjectId包含时间戳)
results = collection.find().sort('_id', DESCENDING)
# 方法2:如果有明确的插入时间字段
# results = collection.find().sort('created_at', DESCENDING)
# 遍历结果
for doc in results:
print(doc)
# 如果只需要最后N条记录
last_5 = collection.find().sort('_id', DESCENDING).limit(5)
MongoDB的_id字段默认使用ObjectId,它包含时间戳信息,所以按_id降序排序就能得到按插入时间倒序的结果。如果你的集合有专门的插入时间字段(比如created_at),直接按那个字段排序也行。
总结:用sort('_id', DESCENDING)就行。

