Pymongo 查询以使用 Python 从 Mongodb 的集合中获取最新文档 [英] Pymongo query to get the latest document from the collection in Mongodb using Python
问题描述
我正在使用 pymongo
并通过以下查询从集合中获取文档:
I am using pymongo
and have below query to get the documents from a collection:
coll_employee = db.get_collection('employeeDetails')
query1 = [{'$match': {'EmployeeId': ObjectId('5edde542f6468910e080e462')}}]
document = coll_employee.aggregate(query1)
tmp1_list = []
for i in document:
tmp1_list.append(i)
print(tmp1_list)
我正在基于 EmployeeId
进行查询,这是一个 ObjectId
.运行上面的代码,我得到了集合的所有文档.有什么办法我们只能获取创建的最新文档.请帮忙.谢谢
I am making a query based on EmployeeId
which is an ObjectId
. Running above code, I am getting all the documents of the collection. Is there any way we can only get the latest document which was created. Please help. Thanks
推荐答案
PyMongo 的语法与 Mongo Shell 的语法略有不同.您不需要为此使用聚合,一个简单的 find()
方法可以与 sort()
和 limit()一起完成这项工作代码>方法.以下查询会有所帮助:
PyMongo's syntax is little bit different than Mongo Shell's syntax. You don't need to use aggregation for this, a simple find()
method will can do the work along with sort()
and limit()
methods. Below query will be helpful:
db.coll_employee.find().sort('_id',-1).limit(1)
您可以使用任何字段,它会随着我们的插入而递增,就像您在评论中所说的那样,您已经 created
字段.因此,您可以使用此字段代替 _id
.
You can use any field, which gets incremented as we insert, like you were saying in comments, you have created
field. So, instead of _id
, you can use this field.
这篇关于Pymongo 查询以使用 Python 从 Mongodb 的集合中获取最新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!