我的 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?
最佳答案
mongoimport
工具有一个选项:
--jsonArray
treat input source as a JSON array
或者可以从包含与 db.collection.find()
命令结果相同的数据格式的文件中导入。这是来自 university.mongodb.com 的示例课件部分内容来自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 }
如您所见,文档之间没有使用数组,也没有逗号分隔符。
我最近发现这符合 the JSON Lines text
格式。
就像 apache.spark.sql.DataFrameReader.json()
方法中使用的一样。
https://stackoverflow.com/questions/30380751/