MongoDB导入数据库异常——Failed: cannot decode array into a D

对于单个json文件,如何导入mongodb数据库?

答:使用mongoimport命令

mongoimport --db [databaseName] --collection [collectionName] --file [filePath]

用命令行进入安装MongoDB的bin目录下,我安装路径是C:Program FilesMongoDBServer4.2in,输入上述命令。输入上面三个参数

[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



结果——导入成功:




作者:艾孜尔江

原文地址:https://www.cnblogs.com/ezhar/p/13110258.html