- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $tsSecond (aggregation)
$tsSecond (aggregation)¶
On this page
Definition¶
-
$tsSecond
¶
New in version 5.1.
Returns the seconds from a timestamp as a long
.
$tsSecond
syntax:
The expression must resolve to a timestamp.
See also
Behavior¶
$tsSecond
returns:
Null
if the input expression evaluates tonull
or refers to a field that is missing.- An error if the input expression does not evaluate to a timestamp.
Examples¶
Obtain the Number of Seconds from a Timestamp Field¶
Create a stockSales
collection that contains company stock financial
market sales:
In the timestamp constructor, the:
- First value is the number of seconds after the :wikipedia:`Unix epoch <Unix_time>`.
- Second value is the incrementing ordinal. When multiple events happen within the same second, the incrementing ordinal uniquely identifies each event.
The following example uses $tsSecond
in a
$project
pipeline stage to return the seconds from the
stock sales saleTimestamp
field:
Example output:
Use $tsSecond
in a Change Stream Cursor to Monitor Collection Changes¶
The example in this section uses $tsSecond
in a
change stream cursor to monitor changes to a
collection.
Create a change stream cursor on a collection
named cakeSales
that you will see later in this section:
In the example, the:
db.collection.watch()
method creates a change stream cursor for thecakeSales
collection and stores the cursor incakeSalesCursor
.$addFields
stage adds a field namedclusterTimeSeconds
tocakeSalesCursor
.$clusterTime
is the timestamp from the oplog entry for thecakeSales
collection change. See Command Response.$tsSecond
returns the seconds from$clusterTime
, which is stored inclusterTimeSeconds
.
Create a cakeSales
collection that contains cake sales in the states
of California (CA
) and Washington (WA
):
To monitor the cakeSales
collection changes, use
cakeSalesCursor
. For example, to obtain the next document from
cakeSalesCursor
, use the next()
method:
The following example output shows the insert
details for the first
document added to the cakeSales
collection. The
clusterTimeSeconds
field contains the seconds from the
clusterTime
field.