You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中提取并打印MongoDB对象内JSON中的汇率值

Extract Specific Exchange Rate from MongoDB Document Using Python

Got it, let's walk through how to pull and print a specific rate from the rates nested field in your MongoDB document with Python. I'll cover two common scenarios: working with the document as a local Python dict, and querying directly from MongoDB to fetch only the data you need.

Scenario 1: Document is already a Python dictionary

If you've already retrieved the document from MongoDB (or parsed it from JSON) and have it as a Python dict, you can access the nested rates field directly. Using .get() is safer than direct indexing because it avoids throwing a KeyError if the currency doesn't exist.

from bson import ObjectId  # Required only if you need to handle the ObjectId

# Your MongoDB document converted to a Python dictionary
exchange_doc = {
    "_id": ObjectId("5addb57d0043582d48ba898a"),
    "success": True,
    "timestamp": 1524477784,
    "base": "EUR",
    "date": "2018-04-23",
    "rates": {
        "AED": 4.492662,
        "AFN": 85.576329,
        "ALL": 128.39508,
        "AMD": 586.837094,
        "ANG": 2.177608,
        "AOA": 267.092358,
        "ARS": 24.678283,
        "AUD": 1.602032,
        "AWG": 2.177639,
        "AZN": 2.079155,
        "BAM": 1.958775,
        "BBD": 2.446786,
        "BDT": 101.517146,
        "BGN": 1.943843,
        "BHD": 0.460968,
        "NOK": 9.626194,
    }
}

# Define the currency you want to fetch
target_currency = "AUD"

# Extract the rate safely
target_rate = exchange_doc["rates"].get(target_currency)

# Print the result with context
if target_rate is not None:
    print(f"1 {exchange_doc['base']} = {target_rate} {target_currency} (as of {exchange_doc['date']})")
else:
    print(f"Currency code '{target_currency}' not found in the rates list")

Scenario 2: Query directly from MongoDB

If you're fetching the document from a MongoDB database, you can optimize the query to only return the fields you care about (instead of pulling the entire document). This reduces data transfer and is more efficient.

from pymongo import MongoClient
from bson import ObjectId

# Connect to your MongoDB instance
client = MongoClient("mongodb://localhost:27017/")  # Update with your connection string
db = client["your_database_name"]  # Replace with your DB name
collection = db["your_collection_name"]  # Replace with your collection name

# Define the target currency and document ID
target_currency = "NOK"
doc_id = ObjectId("5addb57d0043582d48ba898a")

# Query the document, projecting only the base and the target rate
result = collection.find_one(
    {"_id": doc_id},
    {"base": 1, f"rates.{target_currency}": 1, "_id": 0}  # Exclude _id, include base and target rate
)

# Handle the result
if result and "rates" in result and target_currency in result["rates"]:
    print(f"1 {result['base']} = {result['rates'][target_currency]} {target_currency}")
else:
    print(f"Could not find the rate for '{target_currency}' in the specified document")

Key Notes:

  • Always use .get() or check for key existence when accessing nested fields to avoid runtime errors.
  • When querying MongoDB, use projection to fetch only necessary fields—it's a best practice for performance.

内容的提问来源于stack exchange,提问作者Filipe Santos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:05:30