Menu Docs

$currentDate

$currentDate

The $currentDate operator sets the value of a field to the current date, either as a Data or a timestamp. The default type is Data.

Você pode utilizar o $currentDate para implantações hospedadas nos seguintes ambientes:

  • MongoDB Atlas: o serviço totalmente gerenciado para implantações do MongoDB na nuvem

  • MongoDB Enterprise: a versão autogerenciada e baseada em assinatura do MongoDB

  • MongoDB Community: uma versão com código disponível, de uso gratuito e autogerenciada do MongoDB

O operador $currentDate tem o formato:

{ $currentDate: { <field1>: <typeSpecification1>, ... } }

<typeSpecification> can be either:

  • a boolean true to set the field value to the current date as a Date, or

  • a document { $type: "timestamp" } or { $type: "date" } which explicitly specifies the type. The operator is case-sensitive and accepts only the lowercase "timestamp" or the lowercase "date".

Para especificar um <field> em um documento incorporado ou em uma array, use a notação de ponto.

A partir do MongoDB 5.0, os operadores de atualização processam campos de documento com nomes baseados em cadeia de caracteres em ordem lexicográfica. Os campos com nomes numéricos são processados em ordem numérica. Consulte Atualizar Comportamento de Operadores para detalhes.

$currentDate sets the specified field to the date when $currentDate was run.

If the field does not exist, $currentDate adds the field to a document.

A partir do MongoDB 5.0, mongod não gera mais um erro ao usar um operador de atualização como $currentDate com uma expressão de operando vazia ( { } ). Uma atualização vazia não resulta em alteração e nenhuma entrada no oplog é criada (o que significa que é sem operação).

Create a sample collection customers with the following document:

db.customers.insertOne(
{ _id: 1, status: "a", lastModified: ISODate("2013-10-02T01:11:18.965Z") }
)

The following operation updates the lastModified field to the current date, the "cancellation.date" field to the current timestamp as well as updating the status field to "D" and the "cancellation.reason" to "user request".

db.customers.updateOne(
{ _id: 1 },
{
$currentDate: {
lastModified: true,
"cancellation.date": { $type: "timestamp" }
},
$set: {
"cancellation.reason": "user request",
status: "D"
}
}
)

$currentDate sets the specified field to the date when $currentDate was run.

To verify the update:

db.customers.find()

The updated document resembles:

{
"_id" : 1,
"status" : "D",
"lastModified" : ISODate("2020-01-22T21:21:41.052Z"),
"cancellation" : {
"date" : Timestamp(1579728101, 1),
"reason" : "user request"
}
}

The lastModified field is set to the date when $currentDate was run in the update example shown earlier.

Update methods can accept an aggregation pipeline. Specifically, the previous example can be rewritten as the following using the aggregation stage $set and the aggregation variables NOW (for the current datetime) and CLUSTER_TIME (for the current timestamp):

Dica

  • To access aggregation variables, prefix the variable with double dollar signs $$ and enclose in quotes.

  • CLUSTER_TIME is available only on replica sets and sharded clusters.

  • The NOW and CLUSTER_TIME values remain the same throughout the pipeline.

db.customers.updateOne(
{ _id: 1 },
[
{ $set: { lastModified: "$$NOW", cancellation: {date: "$$CLUSTER_TIME", reason: "user request"}, status: "D" } }
]
)

After the operation, you can query the collection to verify the update:

db.customers.find().pretty()

The query should return the following document:

{
"_id" : 1,
"status" : "D",
"lastModified" : ISODate("2020-01-22T21:02:18.994Z"),
"cancellation" : {
"date" : Timestamp(1579726934, 2),
"reason" : "user request"
}
}

Veja também: