Python 使用Pymongo获取集合的所有文档

Python 使用Pymongo获取集合的所有文档,python,mongodb,pymongo,Python,Mongodb,Pymongo,我想编写一个函数来返回mongodb中mycollection中包含的所有文档 from pymongo import MongoClient if __name__ == '__main__': client = MongoClient("localhost", 27017, maxPoolSize=50) db=client.mydatabase collection=db['mycollection'] cursor = collection.find({

我想编写一个函数来返回mongodb中
mycollection
中包含的所有文档

from pymongo import MongoClient

if __name__ == '__main__':
    client = MongoClient("localhost", 27017, maxPoolSize=50)
    db=client.mydatabase
    collection=db['mycollection']
    cursor = collection.find({})
    for document in cursor:
        print(document)

但是,该函数返回:
进程已完成,退出代码为0

以下是示例代码,在命令提示符下运行时效果良好

from pymongo import MongoClient

if __name__ == '__main__':
    client = MongoClient("localhost", 27017, maxPoolSize=50)
    db = client.localhost
    collection = db['chain']
    cursor = collection.find({})
    for document in cursor:
          print(document)

请检查收藏名称。

我认为这将在您的程序中正常工作

cursor = db.mycollection # choosing the collection you need

for document in cursor.find():
    print (document)

pymongo创建了一个游标。因此,您将在光标下获得对象。要获取所有对象,请尝试:

list(db.collection.find({}))
这将强制光标在每个对象上迭代,并将其放入列表()中


玩得开心…

您是否尝试过在“查找”方法中不使用大括号?try cursor=db.mycollection.find()相同的结果:进程结束,退出代码为0Ok,您如何执行此脚本?(同时请调整缩进)我正在使用Pycharm 2.0.3,这是Pycharm特定的使用问题,因为您的代码很好。另外,请检查是否直接以主脚本的形式运行脚本,因为代码中有_name_=='_main_u',请尝试使用控制台检查与数据库的连接。这与我所做的相同,我粘贴了上述代码以确认代码中没有问题。这与当地的环境有关。另外,我提到它可以在命令提示符下正常工作。我理解。最后,它起作用了问题在于集合名称谢谢为什么要为此导入
json
pymongo
?谢谢。解决我的问题这里
cursor=db.mycollection
不要将变量命名为cursor,最好命名为
collection
,只是不要混淆为
cursor.find():
应该是
collection.find():
,它返回一个
cursor
,可以迭代以获取值。