$ROOT - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$ROOT

Amazon DocumentDB 中的$ROOT運算子用於參考彙總管道中的整個輸入文件。它可讓您存取和操作完整的文件,包括其所有巢狀欄位和結構。

參數

範例 (MongoDB Shell)

此範例示範使用 $ROOT來建立稽核日誌,該日誌會擷取完整的原始文件以及處理時的中繼資料。

建立範例文件

db.orders.insertMany([ { _id: 1, orderId: "ORD-2024-001", customer: "María García", email: "maría@example.com", items: [ { product: "Laptop", quantity: 1, price: 1299.99 } ], totalAmount: 1299.99 }, { _id: 2, orderId: "ORD-2024-002", customer: "Arnav Desai", email: "arnav@example.com", items: [ { product: "Mouse", quantity: 2, price: 29.99 }, { product: "Keyboard", quantity: 1, price: 89.99 } ], totalAmount: 149.97 } ]);

查詢範例

db.orders.aggregate([ { $project: { processedAt: new Date(), originalDocument: "$$ROOT", summary: { $concat: [ "Order ", "$orderId", " for ", "$customer", " - Total: $", { $toString: "$totalAmount" } ] } } } ]);

輸出

[ { _id: 1, processedAt: ISODate('2025-11-24T20:43:51.492Z'), originalDocument: { _id: 1, orderId: 'ORD-2024-001', customer: 'María García', email: 'maría@example.com', items: [ { product: 'Laptop', quantity: 1, price: 1299.99 } ], totalAmount: 1299.99 }, summary: 'Order ORD-2024-001 for María García - Total: $1299.99' }, { _id: 2, processedAt: ISODate('2025-11-24T20:43:51.492Z'), originalDocument: { _id: 2, orderId: 'ORD-2024-002', customer: 'Arnav Desai', email: 'arnav@example.com', items: [ { product: 'Mouse', quantity: 2, price: 29.99 }, { product: 'Keyboard', quantity: 1, price: 89.99 } ], totalAmount: 149.97 }, summary: 'Order ORD-2024-002 for Arnav Desai - Total: $149.97' } ]

程式碼範例

若要檢視使用 $ROOT命令的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function createAuditLog() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const orders = db.collection('orders'); const result = await orders.aggregate([ { $project: { processedAt: new Date(), originalDocument: "$$ROOT", summary: { $concat: [ "Order ", "$orderId", " for ", "$customer", " - Total: $", { $toString: "$totalAmount" } ] } } } ]).toArray(); console.log(result); await client.close(); } createAuditLog();
Python
from pymongo import MongoClient from datetime import datetime def create_audit_log(): client = MongoClient('mongodb://username:password@docdb-cluster.cluster-123456789.us-east-1.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['orders'] result = list(collection.aggregate([ { '$project': { 'processedAt': datetime.now(), 'originalDocument': '$$ROOT', 'summary': { '$concat': [ "Order ", "$orderId", " for ", "$customer", " - Total: $", { '$toString': "$totalAmount" } ] } } } ])) print(result) client.close() create_audit_log()