在MongoDB中存储多个JSON文档(带有嵌套JSON键值对象的行数组格式)

时间:2013-10-24 14:11:15

标签: java json mongodb bson

我有json文件,每行看起来像:

[1, "A", "B", 10, "{\"key\":\"val"}"]

如何使用JAVA驱动程序api或其他方式导入文件?

使用以下功能:

public static void importJSONFileToDBUsingJavaDriver(String pathToFile, DB db, String collectionName) {
    // open file
    FileInputStream fstream = null;
    try {
        fstream = new FileInputStream(pathToFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.out.println("file not exist, exiting");
        return;
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

    // read it line by line
    String strLine;
    DBCollection newColl =   db.getCollection(collectionName);
    try {
        while ((strLine = br.readLine()) != null) {
            // convert line by line to BSON
            DBObject bson = (DBObject) JSON.parse(JSONstr);
            // insert BSONs to database
            try {
                newColl.insert(bson);
            }
            catch (MongoException e) {
              // duplicate key
              e.printStackTrace();
            }


        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }


}

导致以下错误(在newColl.insert(bson);行上):

java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]
at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:161)
at org.bson.types.BasicBSONList._getInt(BasicBSONList.java:152)
at org.bson.types.BasicBSONList.get(BasicBSONList.java:104)
at com.mongodb.DBCollection.apply(DBCollection.java:766)
at com.mongodb.DBCollection.apply(DBCollection.java:755)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:242)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
at com.mongodb.DBCollection.insert(DBCollection.java:75)
at com.mongodb.DBCollection.insert(DBCollection.java:59)
at com.mongodb.DBCollection.insert(DBCollection.java:104)

尝试使用mongoimport.exe实用程序:

mongoimport --db db --collection dbColl  < rows.js

导致:

exception:BSON representation of supplied JSON is too large: code FailedToParse: FailedToParse: Expecting '{': offset:0

如果有人可以将我推荐给MongoDB可接受的JSON格式规范,我会很高兴。 (我的意思是它可以转换为BSON,然后可以从它构建DBObject,并且可以将此对象插入到MongoDB集合中)

1 个答案:

答案 0 :(得分:2)

您正在尝试从字符串创建一个DBObject,实际上是一个数组,因此直接使用JSON.parse(JSONstr)无法对其进行类型转换。所以你必须先将你的字符串转换为Object然后插入它。

    String JSONstr = "[1, \"A\", \"B\", 10,{\"key\":\"val\"}]";
    JSONArray jsonArray = new JSONArray(JSONstr);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("data", jsonArray);
    DBObject bson = (DBObject) JSON.parse(jsonObject.toString());
    WriteResult insert = newColl.insert(bson);