Mongodb 蒙戈。如何通过_id的时间戳更新createdAt

Mongodb 蒙戈。如何通过_id的时间戳更新createdAt,mongodb,Mongodb,我的当前数据尚未包含createdAt。现在我想写一个脚本来更新所有现存的记录 我试过: db.getCollection('storageunits').aggregate([ { "$addFields": { "createdAt": "$_id.getTimestamp()" } } ]) 但是它不起作用。从\u id 选择1 对于\u id字段(>=v4.0),您可以与or运算符组合使用: | 选择2 您可以对

我的当前数据尚未包含
createdAt
。现在我想写一个脚本来更新所有现存的记录

我试过:

db.getCollection('storageunits').aggregate([
    {
        "$addFields": {
            "createdAt": "$_id.getTimestamp()"
         }
    }
])
但是它不起作用。

\u id
选择1 对于
\u id
字段(>=
v4.0
),您可以与or运算符组合使用:

|

选择2 您可以对
\u id
字段使用或运算符,并减去
01/01/1970
(>=
v4.0
):

|

使用
createdAt
选择1 向聚合(>=v4.0)添加额外的运算符。
这将使用聚合结果中的文档覆盖整个集合。

{$out: "storageunits"}
选择2 由于MongoDB
v4.2
,我们可以在内部更新方法

db.getCollection('storageunits').update({},
  [
    { "$set": { "createdAt": { $toLong: { $toDate: "$_id" }}}}
  ],
  { "multi" : true}
)

try:ObjectId(“507c7f79bcf86cd7994f6c0e”).getTimestamp()我不需要指定id。$\ id是自身的id,它将使用自身的$\ id更新自身的createdAt$_id是一个动态值,我也可以尝试:“$\u id”.getTimestamp()或ObjectId(“\u id”).getTimestamp()。你用的是哪个mongo verison?我的mongo版本是4.0.4Thanks,它成功了。但是createdAt的类型是Int64。如何使用DateTime类型存储createdAt。它应该是人工日期时间格式。我尝试了:
db.getCollection('storageunits').aggregate([{$addFields:{“createdAt”:{$toDate:$\u id}}}}])
,效果非常好。多谢you@VAnhDũng我的第一个答案是
$toDate
,但后来我严格改为timestamp
{$out: "storageunits"}
db.getCollection('storageunits').update({},
  [
    { "$set": { "createdAt": { $toLong: { $toDate: "$_id" }}}}
  ],
  { "multi" : true}
)