问题描述
我有 authors
和 books
测试集合,它们之间存在多对多关系。
> 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' ]
}
]
我在外部实现了关系,从 authors
和 books
字段可以看出。但是,我错误地将引用数组设为原始字符串,而不是 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"
}
}
}
}
}
])