【问题标题】:MongoDB - Unable to add timestamp fields to subdocuments in an arrayMongoDB - 无法将时间戳字段添加到数组中的子文档
【发布时间】: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


【解决方案1】:

在更新语句中使用聚合运算符并引用另一个字段的值需要使用管道形式的更新,直到 MongoDB 4.2 才可用。

升级后,您可以使用如下更新:

db.collection.updateMany({
  "courses": {$elemMatch: {
        _id:{$exists:true}, 
        createdAt: {$exists: false}
   }}
 },
 [{$set: {
      "courses": {
        $map: {
          input: "$courses",
          in: {
            $mergeObjects: [
              {createdAt: {
                  $convert: {
                    input: "$$this._id",
                    to: "date",
                    onError: {"error": "$$this._id"}
                  }
               }},
               "$$this"
            ]
          }
        }
      }
    }
  }
])

【讨论】:

  • 这正是我所需要的,非常感谢!我今天学到了很多关于 Mongo 的知识。
猜你喜欢
  • 2016-10-16
  • 2014-07-29
  • 2018-08-21
  • 2012-09-28
  • 2017-12-27
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多