1

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

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

如何使用 JAVA driver 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 集合中)

4

1 回答 1

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);
于 2013-10-25T11:42:55.270 回答