首页 > 解决方案 > 在 Python 中使用来自 MongoDB 的数据的 Google Charts

问题描述

我正在尝试从数据库 MongoDB 中设置数据以在 python 中绘制 Google Chart。

import pymongo
from pymongo import MongoClient
import pandas as pd
from string import Template
import pprint


cluster = MongoClient("mongodb+srv://saman:1234@cluster0-vhwfp.mongodb.net/test?retryWrites=true&w=majority")
db= cluster["Test"]
collection= db["Test"]


rm=list(collection.find({}))

chart_data_str= ''
results= collection.find({})
for x in results:
    chart_data_str += '%s,\n' %x
    
print(chart_data_str)

我想知道,如何更改以下格式


{'_id': 5, 'name': 'Mahdi', 'Score': 9},
{'_id': 1, 'name': 'Ali', 'Score': 3},
{'_id': 3, 'name': 'Christian', 'Score': 6},
{'_id': 4, 'name': 'Niklas', 'Score': 1},
{'_id': 2, 'name': 'Dominik', 'Score': 2},
{'_id': 0, 'name': 'Saman', 'Score': 5},

转成这种格式


['Mahdi', 9],
['Ali', 3],
['Christian', 6],
['Niklas', 1],
['Dominik', 2],
['Saman', 5]

谢谢

标签: pythonpandasmongodbcharts

解决方案


如果您只想将其打印为字符串:

for result in collection.find({}, {'_id': 0}):
    print(f"[{result.get('name')}, {result.get('Score')}],")

如果这不是您想要的,请澄清您的问题。


推荐阅读