$subtract - Amazon DocumentDB

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

$subtract

Amazon DocumentDB 中的$subtract運算子用於減去值。它可以用來減去日期、數字或兩者的組合。此運算子有助於計算兩個日期之間的差異,或從數字中減去值。

參數

  • expression1:要減去的第一個值。

  • expression2:要從 中減去的第二個值<expression1>

範例 (MongoDB Shell)

下列範例示範如何使用 $subtract運算子來計算兩個日期之間的差異。

建立範例文件

db.dates.insert([ { "_id": 1, "startDate": ISODate("2023-01-01T00:00:00Z"), "endDate": ISODate("2023-01-05T12:00:00Z") } ]);

查詢範例

db.dates.aggregate([ { $project: { _id: 1, durationDays: { $divide: [ { $subtract: ["$endDate", "$startDate"] }, 1000 * 60 * 60 * 24 // milliseconds in a day ] } } } ]);

輸出

[ { _id: 1, durationDays: 4.5 } ]

在此範例中,運算$subtract子用於計算 $endDate和 之間的差異,以天$startDate為單位。

程式碼範例

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

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); const collection = db.collection('dates'); const pipeline = [ { $project: { _id: 1, durationDays: { $divide: [ { $subtract: ["$endDate", "$startDate"] }, 1000 * 60 * 60 * 24 // Convert milliseconds to days ] } } } ]; const results = await collection.aggregate(pipeline).toArray(); console.dir(results, { depth: null }); } finally { await client.close(); } } example().catch(console.error);
Python
from datetime import datetime, timedelta from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') try: db = client.test collection = db.dates pipeline = [ { "$project": { "_id": 1, "durationDays": { "$divide": [ { "$subtract": ["$endDate", "$startDate"] }, 1000 * 60 * 60 * 24 # Convert milliseconds to days ] } } } ] results = collection.aggregate(pipeline) for doc in results: print(doc) except Exception as e: print(f"An error occurred: {e}") finally: client.close() example()