我有超过 1000 万个格式为 JSON 的文档:
["key": "val2", "key1" : "val", "{\"key\":\"val", \"key2\":\"val2"}"]
在一个文件中。
使用 JAVA Driver API 导入大约需要 3 个小时,同时使用以下功能(一次导入一个 BSON):
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.
}
}
有更快的方法吗?也许,MongoDB 设置可能会影响插入速度?(例如,添加将用作索引的键:“_id”,以便 MongoDB 不必为每个文档创建人工键和索引)或在插入时完全禁用索引创建。谢谢。