$tsSecond

Extracts the seconds portion from a timestamp value, returning the time component in seconds since Unix epoch (January 1, 1970, 00:00:00 UTC).

Syntax

{ $tsSecond: <expression> }

Parameters

expressionobjectrequired

Expression that evaluates to a timestamp, returns error if not a timestamp

Examples

Extract seconds from audit timestamp

Get seconds value from last updated timestamp in audit log

Query:

db.stores.aggregate([{ $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} }, { $project: { name: 1, lastUpdatedSeconds: { $tsSecond: "$lastUpdated" }, lastUpdatedDate: { $toDate: { $multiply: [{ $tsSecond: "$lastUpdated" }, 1000] } } } }])

Output:

Document with seconds value and converted date from timestamp

Convert timestamp to readable date

Extract seconds and convert to standard date format

Query:

db.events.aggregate([{ $project: { eventName: 1, timestampSeconds: { $tsSecond: "$eventTime" }, readableDate: { $dateToString: { format: "%Y-%m-%d %H:%M:%S", date: { $toDate: { $multiply: [{ $tsSecond: "$eventTime" }, 1000] } } } } } }])

Output:

Documents with both timestamp seconds and human-readable date formats

Related