简体   繁体   English

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

[英]Get all documents of a collection using Pymongo

I want to write a function to return all the documents contained in mycollection in mongodb 我想编写一个函数以返回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)

However, the function returns: Process finished with exit code 0 但是,该函数返回: Process finished with exit code 0

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. 请检查集合名称。

I think this will work fine in your program. 我认为这将在您的程序中正常工作。

cursor = db.mycollection # choosing the collection you need

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

pymongo creates a cursor. pymongo创建一个游标。 Hence you'll get the object 'under' the cursor. 因此,您将在光标下方获得对象。 To get all objects in general try: 一般而言,要获取所有对象,请尝试:

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

This will force the cursor to iterate over each object and put it in a list() 这将强制光标遍历每个对象并将其放在list()中

Have fun... 玩得开心...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM