【发布时间】:2022-01-15 14:00:15
【问题描述】:
我最近更新了我的子模式(称为课程)以添加时间戳,并尝试回填现有文档以包含 createdAt/updatedAt 字段。
课程存储在用户文档中名为courses 的数组中。
// User document example
{
name: "Joe John",
age: 20,
courses: [
{
_id: <id here>,
name: "Intro to Geography",
units: 4
} // Trying to add timestamps to each course
]
}
我还想从课程的 Mongo ID 派生 createdAt 字段。
这是我用来尝试将时间戳添加到子文档的代码:
db.collection('user').updateMany(
{
'courses.0': { $exists: true },
},
{
$set: {
'courses.$[elem].createdAt': { $toDate: 'courses.$[elem]._id' },
},
},
{ arrayFilters: [{ 'elem.createdAt': { $exists: false } }] }
);
但是,运行代码后,课程子文档中没有添加任何字段。
我正在使用mongo ^4.1.1 和mongoose ^6.0.6。
任何帮助将不胜感激!
【问题讨论】:
-
$toDate是一个聚合函数,只能在aggregate中使用,不能在updateMany中使用
标签: mongodb mongoose mongodb-query