我有 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 集合中)