我有一個 CSV 檔案,其中有一列填充有陣列資料,如['foo', 'bar', 'baz']檔案中所示。
Manufacturer;EngineCount;ImagesURL
Boeing,2,['https://url.com/image1', 'https://url.com/image2', 'https://url.com/image3']
Airbus,4,['https://url.com/image1', 'https://url.com/image2', 'https://url.com/image3']
我找不到在 MongoDB (4.2 ) 中將它作為陣列匯入的方法,它總是作為 string 匯入
"['https://url.com/image1', 'https://url.com/image2', 'https://url.com/image3']"。也許 .csv 檔案不可能。
JSON.parse所以我在stackoverflow上找到了一個解決方案,我們更新欄位以使用函式將它們決議為陣列。但是我是 MongoDB 新手,我無法成功用 MongoDB 中的舊值更新欄位:
我試過了
db.planes.updateMany({}, {$set: {ImagesURL:JSON.parse("$ImagesURLS")}})。
這是回傳錯誤SyntaxError: Unexpected token $ in JSON at position 0
我的錯誤在哪里?
謝謝你。
uj5u.com熱心網友回復:
選項 1:轉換輸入 abit 并使用選項--useArrayIndexFields如下:
input.csv:(洗掉括號并在每個陣列欄位的 ImagesURL 標頭中添加索引)
Manufacturer,EngineCount,ImagesURL.0,ImagesURL.1,ImagesURL.2
Boeing,2,'https://url.com/image1', 'https://url.com/image2', 'https://url.com/image3'
Airbus,4,'https://url.com/image1', 'https://url.com/image2', 'https://url.com/image3'
并做:
mongoimport --db=myDB --col=planes --type=csv --headerline --useArrayIndexFields --file=input.csv
您將匯入的檔案為:
{Manufacturer:"Boeing",EngineCount:2,ImagesURL:['https://url.com/image1', 'https://url.com/image2', 'https://url.com/image3']}
{Manufacturer:"Airbus",EngineCount:4,ImageURL:['https://url.com/image1', 'https://url.com/image2', 'https://url.com/image3']}
選項2:基于欄位型別的匯入后更新是字串
// 作為字串插入的檔案:"["https://url.com/image1","https://url.com/image2"]"
var ops = [];
db.planes.find({ "ImagesURL": { "$type": 2} }).forEach(doc => {
var ImagesURL = doc.ImagesURL.split(',').map( e => e.replace(/"|\[|\]|\\/gm,'').toString() );
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "ImagesURL": ImagesURL } }
}
});
if ( ops.length >= 100 ) {
db.planes.bulkWrite(ops);
ops = [];
}
});
if ( ops.length > 0 ) {
db.planes.bulkWrite(ops);
ops = [];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/487374.html
