System variables in Aggregation Pipeline

Hi Team,

Can you please help me understand the difference between the below system level variables.

$$CURRENT vs $$ROOT
$$NOW vs $$CLUSTERTIME

Referenced from → https://docs.mongodb.com/manual/reference/aggregation-variables/#mongodb-variable-variable.CURRENT

Hi @Laks

$$NOW is always awaílable whereas $$CLUSTER_TIME is bound to the individual clusters as in replicated and sharded clusters, not for single instances.

$$ROOT References the root document
$$CURRENT References the start of the field path, which by default is ROOT

field path is the “access point” for your aggregation. When you want to do some aggregation on $item.quantity this will be the the field path. You could also write this as "$$CURRENT.quantity" where $$CURRENT defaults to the root of the current object. But you can change $$CURRENT whereas $$ROOT is constant

Regards,
Michael

2 Likes

Thanks @Michael for your response. This is helpful. One follow up question if you don’t mind, $$NOW on replica sets and shared clusters will also return the same value as $$CLUSTERTIME.

So is there any significance behind having separate system variable ? i.e., one for single instances and other for cluster setup ?

Hello @Laks
good question, personally I never ran into a problem using $$NOW. I don’t know the answer but will see if I can find someone who knows.
Regards,
Michael

Hello @Laks

On your question

So is there any significance behind having separate system variable ? i.e., one for single instances and other for cluster setup ?

I can now compile an answer, many thanks to @Asya_Kamsky for details and @Stennie for a very elaborate and helpful explanation.

TL;DR

The key answer to your question is to understand the difference between the local time of an environment running a MongoDB process vs. the logical time on distributed system to ensure causal consistency on distributed events.

$$NOW is wall time and returns a BSON Date value
$$CLUSTER_TIME is reflecting logical cluster clock time and returns a BSON Timestamp

The details

You will find further details/information

about vector clock and causal consistency in the MonogDB github repro:

about Logical clock on wikipedia:

about Lamport Clock / timestamp (my favourite):

Regards,
Michael

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.