我正在尝试使用 _id
字段向所有现有文档添加新字段 createdDate
。我这样做是为了使文档易于阅读。我尝试了以下代码片段,但它不起作用。
dbase.collection("cname").updateMany(
{},
{ $set: { createdDate: new Date(parseInt("$_id".substring(0, 8), 16) * 1000) } }
)
.then((resp)=>{ console.log('complete') })
这是我现在所有文档的createdDate
(运行查询后):“1970-01-01T00:00:00.000+00:00”
我的代码有什么问题?
最佳答案
您需要使用update with aggregation pipeline从 MongoDB 4.2 开始,
- $toDate将类型转换为
_id
的日期
dbase.collection("cname").updateMany(
{},
[{
$set: { createdDate: { $toDate: "$_id" } }
}]
)
.then((resp) => { console.log('complete') });
关于javascript - 将 _id 中的创建日期字段添加到所有 mongo 文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64836293/