問題描述
[MongoDB]:更改所有數組字段中的值類型 ([MongoDB]: Changing the type of values in all array fields)
我有 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.",
inPrint: true,
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' ],
books: [ '60a676f24312c6d8ea7bd6ec' ]
},
{
_id: ObjectId("60a673c44312c6d8ea7bd6eb"),
name: 'Max Schwarz',
age: 42,
job: 'pilot',
books: [ '60a676f24312c6d8ea7bd6ed' ]
}
]
我在外部實現該關係,如 authors
和 books
字段所示。但是,我犯了一個錯誤,即讓引用數組是原始字符串,而不是 ObjectId
類型。這意味著我的連接(例如,$lookup()
) 失敗。
我嘗試批量更新所有字符串以使它們成為 ObjectId
s 使用命令:
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"),
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.",
inPrint: true,
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' ],
books: [ '60a676f24312c6d8ea7bd6ec' ]
},
{
_id: ObjectId("60a673c44312c6d8ea7bd6eb"),
name: 'Max Schwarz',
age: 42,
job: 'pilot',
books: [ '60a676f24312c6d8ea7bd6ed' ]
}
]
</code></pre>
參考解法
方法 1:
If you decide to update all books string to ObjectId, u can use update‑documents‑with‑aggregation‑pipeline
db.authors.updateMany({},[
{
"$addFields": {
"books": {
"$map": {
"input": "$books",
"in": {
"$toObjectId": "$$this"
}
}
}
}
}
])
參考文件