$subtract - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

$subtract

Amazon DocumentDB의 $subtract 연산자는 값을 빼는 데 사용됩니다. 날짜, 숫자 또는 둘의 조합을 빼는 데 사용할 수 있습니다. 이 연산자는 두 날짜 간의 차이를 계산하거나 숫자에서 값을 빼는 데 유용합니다.

파라미터

  • expression1: 뺄 첫 번째 값입니다.

  • expression2:에서 뺄 두 번째 값입니다<expression1>.

예제(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()