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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37941610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:07:24  来源:igfitidea点击:

Get all documents of a collection using Pymongo

pythonmongodbpymongo

提问by MAYA

I want to write a function to return all the documents contained in mycollectionin mongodb

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

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)

However, the function returns: Process finished with exit code 0

但是,该函数返回: Process finished with exit code 0

回答by notionquest

Here is the sample code which works fine when you run from command prompt.

这是从命令提示符运行时可以正常工作的示例代码。

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)

Please check the collection name.

请检查集合名称。

回答by Robert Nagtegaal

pymongo creates a cursor. Hence you'll get the object 'under' the cursor. To get all objects in general try:

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

list(db.collection.find({}))

This will force the cursor to iterate over each object and put it in a list()

这将强制光标遍历每个对象并将其放入 list()

Have fun...

玩得开心...

回答by Isuru Maldeniya

I think this will work fine in your program.

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

cursor = db.mycollection # choosing the collection you need

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