[MongoDB]:更改所有数组字段中的值类型

问题描述

我有 authorsbooks 测试集合,它们之间存在多对多关系。

> db.books.find()
[
  {
    _id: ObjectId("60a676f24312c6d8ea7bd6ec"),title: '300 years of peanut juggling: A longitudinal analysis.',inPrint: true,authors: [ '60a673c44312c6d8ea7bd6e9','60a673c44312c6d8ea7bd6ea' ]
  },{
    _id: ObjectId("60a676f24312c6d8ea7bd6ed"),title: "Mystery Overflow: murder and chaos on the Web's biggest developer Q & A platform.",authors: [ '60a673c44312c6d8ea7bd6eb' ],edition: 2
  }
]
> db.authors.find()
[
  {
    _id: ObjectId("60a673c44312c6d8ea7bd6e9"),name: 'Jason Filippou',age: 33,nationalities: [ 'GRC,CND' ],books: [ '60a676f24312c6d8ea7bd6ec' ]
  },{
    _id: ObjectId("60a673c44312c6d8ea7bd6ea"),name: 'Mary Chou',age: 39,nationalities: [ 'USA' ],{
    _id: ObjectId("60a673c44312c6d8ea7bd6eb"),name: 'Max Schwarz',age: 42,job: 'pilot',books: [ '60a676f24312c6d8ea7bd6ed' ]
  }
]

我在外部实现了关系,从 authorsbooks 字段可以看出。但是,我错误地将引用数组设为原始字符串,而不是 ObjectId 类型。这意味着我按照要求加入,例如 $lookup()) 失败。

我尝试使用以下命令批量更新所有字符串以使其ObjectId

db.books.find({}).forEach(book => book.authors.forEach(id => ObjectId(id)))

虽然命令有效,但原始数据没有改变:

> db.books.find({}).forEach(book => book.authors.forEach(id => ObjectId(id)))

> db.books.find()
[
  {
    _id: ObjectId("60a676f24312c6d8ea7bd6ec"),books: [ '60a676f24312c6d8ea7bd6ed' ]
  }
]

我的错误是什么?

解决方法

如果您决定将所有书籍字符串更新为 ObjectId,您可以使用 update-documents-with-aggregation-pipeline

db.authors.updateMany({},[
  {
    "$addFields": {
      "books": {
        "$map": {
          "input": "$books","in": {
            "$toObjectId": "$$this"
          }
        }
      }
    }
  }
])

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...