0%

MongoDB匯出CSV

MongoDB匯出CSV

MongoDB有內建mongoexport來輸出csv檔,但輸出csv要指定欄位才可以順利輸出

假設在本地端有一個資料庫是名字是customer,collection是users,目前裡面有一筆資料

1
2
3
4
{
"name": "ken",
"age": "25"
}

如果要匯出這name跟age的欄位就可以使用下列指令

1
mongoexport --host localhost --db customer --collection user  --type=csv --out customer.csv --fields name,age

這樣就會在目前terminal的所在位置輸出一個名為customer.csv的檔案

如果這個資料庫有權限設定,使用者的帳戶是ken,密碼是lee 那就輸入下列指令

1
mongoexport --host localhost --db customer --collection user  --username ken --password lee --type=csv --out customer.csv --fields name,age

假設今天資料庫的資料是

1
2
3
4
5
6
7
8
{
"name": "ken",
"age": "25",
"car": {
"car1": "991",
"car2": "easy100"
}
}

如果只要輸出car裡面的car1、car2,那就輸入

1
mongoexport --host localhost --db customer --collection user  --username ken --password lee --type=csv --out customer.csv --fields car.car1,car.car2

匯入匯出MONGODB資料成JSON CSV檔案
how use mongoexport to export only specific fields in a sub-document