本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$subtract
Amazon DocumentDB 中的$subtract运算符用于减去值。它可以用来减去日期、数字或两者的组合。此运算符可用于计算两个日期之间的差值或从数字中减去一个值。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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()