如果我有這樣的檔案:
db.people.insertOne({name: "Annie", latestScore: 5});
然后根據這個答案,我可以移動latestScore到這樣的陣列欄位:
db.people.updateOne(
{name: 'Annie'},
[
{$set:
{scoreHistory:
{$concatArrays: [
{$ifNull: ["$scoreHistory", []]},
["$latestScore"]
]}
}
},
{ $unset: ["latestScore"] }
]
);
這是生成的檔案:
{
_id: ObjectId("61d2737611e48e0d0c30b35b"),
name: 'Annie',
scoreHistory: [ 5 ]
}
我們可以對嵌套在陣列中的物件執行相同的更新嗎?例如,如果檔案是這樣的:
db.people.insertOne({
name: 'Annie',
words: [
{word: "bunny", score: 5},
{word: "pink", score: 5}
]
});
我們如何將其更新為:
{
name: 'Annie',
words: [
{word: "bunny", scoreHistory: [5]},
{word: "pink", scoreHistory: [5]}
]
}
我知道我可以從應用程式迭代和修改陣列并一次更新整個陣列,但我想使用上面第一個示例中的運算子來完成它。
該網站首先顯示words.word并按words.score行顯示,單擊一行顯示words.scoreHistory在彈出視窗中。我期望單詞陣列小于 500。也歡迎任何有關重構架構以簡化上述操作的建議!
uj5u.com熱心網友回復:
db.collection.update({
name: "Annie"
},
[
{
$set: {
words: {
$map: {
input: "$words",
as: "m",
in: {
word: "$$m.word",
scoreHistory: {
$concatArrays: [
{
$ifNull: [
"$$m.scoreHistory",
[]
]
},
[
"$$m.score"
]
]
}
}
}
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/401973.html
