翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$subtract
Amazon DocumentDB の $subtract演算子は、値を減算するために使用されます。日付、数値、またはその両方の組み合わせを減算するために使用できます。この演算子は、2 つの日付の差を計算する場合や、数値から値を引く場合に便利です。
パラメータ
例 (MongoDB シェル)
次の例は、 $subtract演算子を使用して 2 つの日付の差を計算する方法を示しています。
サンプルドキュメントを作成する
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()