Reputation: 1257
My current data does not included createdAt
yet. Now I want to write a script to update all exist records.
I tried with:
db.getCollection('storageunits').aggregate([
{
"$addFields": {
"createdAt": "$_id.getTimestamp()"
}
}
])
but it didn't work.
Upvotes: 2
Views: 1311
Reputation: 13103
timestamp
from _id
You can use $toLong with combination of $toDate or $convert operators for _id
field (>= v4.0
):
db.getCollection('storageunits').aggregate([
{
$addFields: {
"createdAt": {
$toLong: {
$toDate: "$_id"
}
}
}
}
])
MongoPlayground | with $convert
You can use $toDate or $convert operators for _id
field and subtract 01/01/1970
(>= v4.0
):
db.getCollection('storageunits').aggregate([
{
$addFields: {
"createdAt": {
$subtract: [
{
$toDate: "$_id"
},
new Date("1970-01-01")
]
}
}
}
])
MongoPlayground | Convert date to timestamp
createdAt
Add extra operator to your aggregation (>= v4.0).
This will override entire collection with documents from aggregation result
{$out: "storageunits"}
Since MongoDB v4.2
, we can perform aggregation inside update method
db.getCollection('storageunits').update({},
[
{ "$set": { "createdAt": { $toLong: { $toDate: "$_id" }}}}
],
{ "multi" : true}
)
Upvotes: 1