我在 mongodb 中有一組影像,我正在嘗試更改陣列的架構。現在影像存盤如下
["https://images.freeimages.com/images/large-previews/e51/tokyo05-2-1447803.jpg","https://images.freeimages.com/images/large-previews/aae/lomo-spider-1386711.jpg","https://images.freeimages.com/images/large-previews/383/the-home-of-the-candle-1-1425911.jpg"]
我想要的最終輸出如下所示。
[
{
url:
"https://images.freeimages.com/images/large-previews/e51/tokyo05-2-1447803.jpg",
index: "1"
},
{
url:
"https://images.freeimages.com/images/large-previews/aae/lomo-spider-1386711.jpg",
index: "2"
},
{
url:
"https://images.freeimages.com/images/large-previews/383/the-home-of-the-candle-1-1425911.jpg",
index: "3"
},
]
我怎么能在 mongosh 中做到這一點?
將其作為 Python 陣列執行然后匯入回 mongodb 是否更容易?感謝您的時間!
uj5u.com熱心網友回復:
從 mongoDB 4.2 版開始,您可以從 mongosh 執行以下操作:
db.collection.update({},
[
{
$addFields: {
x: {
"$map": {
"input": "$x",
"as": "y",
"in": {
url: "$$y",
index: {
$indexOfArray: [
"$x",
"$$y"
]
}
}
}
}
}
}
],
{
multi: true
})
解釋:
- 通過 addFields 用新格式的物件陣列替換檔案中的陣列 x(我們在這里假設陣列欄位鍵是 x)(使用 $indexOfArray 生成新“索引”欄位的內容。
- 添加 {multi:true} 以更新集合中的所有檔案
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487247.html
