使用mongoimport将json从文件导入mongodb

时间:2015-05-21 17:40:08

标签: mongodb

我有这样的json_file.json:

[
{
    "project": "project_1",
    "coord1": 2,
    "coord2": 10,
    "status": "yes",
    "priority": 7
},
{
    "project": "project_2",
    "coord1": 2,
    "coord2": 10,
    "status": "yes",
    "priority": 7
},
{
    "project": "project_3",
    "coord1": 2,
    "coord2": 10,
    "status": "yes",
    "priority": 7
}
]

当我运行以下命令将其导入mongodb时:

mongoimport --db my_db --collection my_collection --file json_file.json 

我收到以下错误:

Failed: error unmarshaling bytes on document #0: JSON decoder out of sync - data changing underfoot?

如果我将--jsonArray标志添加到我导入的命令中,如下所示:

imported 3 documents

而不是原始文件中显示的具有json格式的文档。

如何在上面显示的文件中以原始格式将json导入mongodb?

4 个答案:

答案 0 :(得分:102)

The mongoimport tool has an option:
--jsonArray treat input source as a JSON array
Or it is possible to import from file
containing same data format as
the result of db.collection.find() command.
Here is example from university.mongodb.com courseware
some content from grades.json:

{ "_id" : { "$oid" : "50906d7fa3c412bb040eb577" }, "student_id" : 0, "type" : "exam", "score" : 54.6535436362647 }
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb578" }, "student_id" : 0, "type" : "quiz", "score" : 31.95004496742112 }
{ "_id" : { "$oid" : "50906d7fa3c412bb040eb579" }, "student_id" : 0,       "type" : "homework", "score" : 14.8504576811645 }

As you can see,
no array used and
no comma delimiters between documents either.

I discover, recently,
that this complies with the JSON Lines text format .
Like one used in apache.spark.sql.DataFrameReader.json() method .

答案 1 :(得分:73)

也许来自MongoDB项目博客的以下参考资料可以帮助您深入了解数组在Mongo中的工作方式:

https://blog.mlab.com/2013/04/thinking-about-arrays-in-mongodb/

否则我会构建你的导入框架,并且:或者

a)使用--jsonArray标志将三个不同的对象分别导入到集合中;或

b)将完整数组封装在单个对象中,例如以这种方式:

{
"mydata": 
    [
    {
          "project": "project_1",
          ...
          "priority": 7
    }
    ]
}

HTH。

答案 2 :(得分:8)

我今天遇到了相反的问题,我的结论是:

如果您希望一次插入JSON对象数组,其中每个数组条目应被视为单独的dtabase条目,您有两种语法选项:

  1. 具有有效昏迷位置的对象数组& --jsonArray flag必须

    [
      {obj1},
      {obj2},
      {obj3}
    ]
    
  2. 使用基本上不正确的JSON格式的文件(即JSON对象实例之间缺少,&没有--jsonArray标志

    {obj1}
    {obj2}
    {obj3}
    
  3. 如果你只希望插入一个数组(即数组作为数据库的顶级公民),我认为这是不可能的,也是无效的,因为根据定义,mongoDB支持将文档作为顶级对象,然后映射到JSON对象。换句话说,您必须像ALAN WARD指出的那样将数组包装到JSON对象中。

答案 3 :(得分:0)

错误:

$ ./mongoimport --db bookings --collection user --file user.json

2021-06-12T18:52:13.256+0530    connected to: localhost
2021-06-12T18:52:13.261+0530    Failed: error unmarshaling bytes on document #0: JSON decoder out of sync - data changing underfoot?
2021-06-12T18:52:13.261+0530    imported 0 documents

解决方案:当您的 JSON 数据包含一个对象数组时,我们需要使用 --jsonArray 同时使用如下所述的命令导入

$ ./mongoimport --db bookings --collection user --file user.json --jsonArray
2021-06-12T18:53:44.164+0530    connected to: localhost
2021-06-12T18:53:44.532+0530    imported 414 documents