【问题标题】:Can`t print values from collections in pymongo无法从 pymongo 中的集合中打印值
【发布时间】:2019-09-01 08:40:14
【问题描述】:

我正在尝试获取 mongodb 中存在的所有数据库的值,遍历所有数据库和集合,而不是打印它的文档。我可以打印将集合作为变量传递的文档,但不能遍历所有数据库和集合(作为变量的值)。有人知道 pymongo 是否支持动态地作为值传递而不是将集合和数据库作为变量本身传递??

client = MongoClient('mongodb://localhost:27017/')

names = client.database_names()
for dbName in names:
    print(dbName)
    db = client.dbName
    collectionNames = client[dbName].collection_names()
    for colecao in collectionNames: 
        print(colecao)
        cursor = db.colecao # choosing the collection you need
        print(cursor)
        cursor2 = cursor.find()  # get documents
        for document in cursor2:
            pprint(document)

数据库名称和集合名称正常打印,但打印光标返回: "Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), u'dbName'), u'colecao')"

它与变量的名称一起使用。

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    代替

    client.dbName

    使用

    client.get_database(dbName)

    而不是

    光标 = db.colecao

    使用

    光标 = db.get_collection(colecao)

    【讨论】:

      猜你喜欢
      • 2016-08-01
      • 2017-12-19
      • 2022-11-02
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多