The find https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.find方法返回一个Cursor https://pymongo.readthedocs.io/en/stable/api/pymongo/cursor.html#pymongo.cursor.Cursor实例,它允许您迭代所有匹配的文档。
要获取第一个符合给定条件的文档,您需要使用find_one https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.find_one。的结果find_one
是一本字典。
您可以随时使用list
构造函数返回集合中所有文档的列表,但请记住,这将加载内存中的所有数据,并且可能不是您想要的。
如果您需要重用游标并且有充分的理由不使用游标,则应该这样做rewind() https://pymongo.readthedocs.io/en/stable/api/pymongo/cursor.html?highlight=rewind#pymongo.cursor.Cursor.rewind
演示使用find
:
>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
... print(doc) # or do something with the document
...
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}
演示使用find_one
:
>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}