如何使用Python将JSON文件导入MongoDB?附currencies.json示例
Hey there! Let's walk through how to get your currencies.json file into MongoDB using Python. I'll cover two common approaches depending on how you want to structure your data in the database.
First, Install Required Tools
Before we start, make sure you have the pymongo package installed (it's the official MongoDB driver for Python). Run this command in your terminal:
pip install pymongo
If you're using MongoDB Atlas (a cloud-hosted MongoDB service), you'll need extra SRV support:
pip install pymongo[srv]
Option 1: Insert the Entire JSON as a Single Document
This is great if you want to keep all exchange rates grouped together (maybe with metadata like a date for the rate snapshot).
Code Example:
import json from pymongo import MongoClient # Connect to your MongoDB instance # For local MongoDB: client = MongoClient("mongodb://localhost:27017/") # For MongoDB Atlas, replace with your cluster's connection string: # client = MongoClient("mongodb+srv://your_username:your_password@cluster0.mongodb.net/") # Select or create a database and collection db = client["currency_database"] collection = db["exchange_rate_snapshots"] # Load the JSON data from your file with open("currencies.json", "r") as file: currency_rates = json.load(file) # Wrap the rates in a document (add metadata like a date if you want) snapshot_document = { "snapshot_date": "2024-05-20", # Replace with actual date if needed "base_currency": "EUR", # Assuming your rates are relative to EUR, adjust as needed "rates": currency_rates } # Insert the document into the collection collection.insert_one(snapshot_document) print("Successfully inserted the currency rate snapshot!")
Option 2: Split Each Currency into Individual Documents
This approach is better if you want to query individual currency rates easily (e.g., "find the rate for AUD"). Each currency becomes its own document in the collection.
Code Example:
import json from pymongo import MongoClient # Connect to MongoDB (same as above) client = MongoClient("mongodb://localhost:27017/") db = client["currency_database"] collection = db["individual_currency_rates"] # Load the JSON data with open("currencies.json", "r") as file: currency_rates = json.load(file) # Convert the key-value pairs into a list of documents currency_documents = [ { "currency_code": code, "exchange_rate": rate, "base_currency": "EUR" # Add base currency info if relevant } for code, rate in currency_rates.items() ] # Insert all documents in one go collection.insert_many(currency_documents) print(f"Inserted {len(currency_documents)} individual currency rate documents!")
Important Notes
- Check Your JSON: Make sure
currencies.jsonis valid JSON (no trailing commas, properly quoted keys/values). Your sample ends with"USD": 1.23...—replace the ellipsis with the actual value to avoid parsing errors. - Authentication: If your MongoDB instance requires a username and password, include them in the connection string (e.g.,
mongodb://user:pass@localhost:27017/). - Existing Data: If you want to avoid duplicate entries, use
update_one()withupsert=Trueinstead ofinsert_one(), or check for existing documents before inserting.
内容的提问来源于stack exchange,提问作者Filipe Santos

