對於單個json文件,如何導入mongodb數據庫?
答:使用mongoimport命令
mongoimport --db [databaseName] --collection [collectionName] --file [filePath]
用命令行進入安裝MongoDB的bin目錄下,我安裝路徑是C:\Program Files\MongoDB\Server\4.2\bin,輸入上述命令。輸入上面三個參數
[databaseName] => 數據庫名
[collectionName] => 集合名
[filePath] => 文件路徑
示例【指令也可以簡寫成只寫首字母的形式】:
mongoimport --db playground --collection user --file ./test.json
playground為我創建的數據庫,user為集合名,./test.json為我json文件所在路徑
導入的時候可能會報錯,說“mongodb Failed: cannot decode array into a D”;

原因:這是因為導入了一個json的數組,只需把參數–file改成–jsonArray即可
打開看一下我們要導入的數據庫集合的具體內容:
[{
"name": "Alexander",
"author": "Ezharjan",
"isPublished": true
}, {
"name": "Javascript",
"author": "Alexander",
"isPublished": true
}, {
"name": "Javascript",
"author": "Alexander",
"isPublished": true
}, {
"name": "C#",
"author": "Alex",
"isPublished": true
}, {
"name": "C#",
"author": "Ezharjan",
"isPublished": true
}]
發現確實不是file而是數組,解決方案:
mongoimport --db test --collection user --jsonArray ./test.json
結果——導入成功:

作者:艾孜爾江
