【问题标题】:Download json file from MongoDB atlas with python使用 python 从 MongoDB atlas 下载 json 文件
【发布时间】:2020-09-13 13:45:34
【问题描述】:

我想下载整个集合并将其放入一个 json 文件中。我试过了(见下文),但它不起作用。

import json
from pymongo import MongoClient
import pymongo
from pathlib import Path

myclient = MongoClient("mongodb+srv://<DbName>:<DbPass>@<DbName>.a3b2ai.mongodb.net/<DbName>?retryWrites=true&w=majority")

db = myclient["PlayerPrices"]

Collection = db["Playstation"]

payload = db.inventory.find( {} ) #I think this command is the problem
with open(str(Path(__file__).parents[1]) + '\Main\playstation_1.json', 'r+') as file:
                json.dump(payload, file, indent=4)
    

【问题讨论】:

    标签: python json mongodb


    【解决方案1】:

    问题是您需要将 Pymongo 光标转换为支持 json 格式。

    # Python Program for 
    # demonstrating the  
    # PyMongo Cursor to JSON 
    
    
    # Importing required modules 
    from pymongo import MongoClient 
    from bson.json_util import dumps, loads 
    
    
    # Connecting to MongoDB server 
    # client = MongoClient('host_name', 
    # 'port_number') 
    client = MongoClient('localhost', 27017) 
    
    # Connecting to the database named 
    # GFG 
    mydatabase = client.GFG 
    
    # Accessing the collection named 
    # gfg_collection 
    mycollection = mydatabase.College 
    
    # Now creating a Cursor instance 
    # using find() function 
    cursor = mycollection.find() 
    
    # Converting cursor to the list  
    # of dictionaries 
    list_cur = list(cursor) 
    
    # Converting to the JSON 
    json_data = dumps(list_cur, indent = 2)  
    
    # Writing data to file data.json 
    with open('data.json', 'w') as file: 
      file.write(json_data)
    

    资源取自:https://www.geeksforgeeks.org/convert-pymongo-cursor-to-json/

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 2017-05-18
      • 2020-11-12
      • 2020-09-11
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多