如何在pymongo中循环循环mongodb的所有集合和集合数据

时间:2019-10-17 16:08:26

标签: python pymongo

我正在读取mongodb数据库的所有集合,并同时在for循环中循环集合名称,以使用pymongo动态获取每个集合数据。

这正在pymongo上的python 3.7和mongodb 3.4上运行

from pymongo import MongoClient
from bson.objectid import ObjectId
import json


client = MongoClient("localhost", 27017, maxPoolSize=50)
#print(client)
mydatabase = client["testdb"]

collections = mydatabase.collection_names(include_system_collections=False)

for collectionName in collections:
    print(collectionName)

    mydata = mydatabase.collectionName.find({})

    for value in mydata:
        print(value)
        for key,valueOFproject in value:
            print(key)
            print(value)

Db

第一收藏

{
    "_id" : "hiphdkTest_HIPHDK_76P1_P00_19WW09Test",
    "project" : "hiphdktest",
    "config" : "HIPHDK_76P1_P00_19WW09test",
    "manual" : {
        "tag1" : "fdsfsdfsd",
        "No" : "No",
        "prqdata1" : "fsdfadfasdfasdfsdfsd",
        "admin1" : "dbhiphdk"
    }
}

第二个收藏

{
    "_id" : "hiphdk_HIPHDK_76P1_P00",
    "project" : "hiphdk",
    "config" : "HIPHDK_76P1_P00",
    "manual" : {
        "tag1" : "fdsfsdfsd",
        "No" : "No",
        "prqdata1" : "fsdfadfasdfasdfsdfsd",
        "admin1" : "dbhiphdk"
    }
}

第三个收藏

{
    "_id" : "hiphdk_HIPHDK_76P1_P00_19WW09",
    "project" : "hiphdk",
    "config" : "HIPHDK_76P1_P00_19WW09",
    "manual" : {
        "tag1" : "fdsfsdfsd",
        "No" : "No",
        "prqdata1" : "fsdfadfasdfasdfsdfsd",
        "admin1" : "dbhiphdk"
    }
}

仅获取集合名称

hiphdk_HIPHDK_76P1_P00_19WW09 hiphdk_HIPHDK_76P1_P00 hiphdkTest_HIPHDK_76P1_P00_19WW09Test

它应该打印出集合名称和每个集合的数据。

1 个答案:

答案 0 :(得分:1)

关键的更改是此行export function createAndDownloadBlobFile(body, filename, extension = 'pdf') { const blob = new Blob([body]); const fileName = `${filename}.${extension}`; if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, fileName); } else { const link = document.createElement('a'); // Browsers that support HTML5 download attribute if (link.download !== undefined) { const url = URL.createObjectURL(blob); link.setAttribute('href', url); link.setAttribute('download', fileName); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } } export function base64ToArrayBuffer(base64) { const binaryString = window.atob(base64); // Comment this if not using base64 const bytes = new Uint8Array(binaryString.length); return bytes.map((byte, i) => binaryString.charCodeAt(i)); }

看看这是否满足您的需求:

mydata = mydatabase[collectionName].find({})