[英]Store multiple JSON documents (in row arrays format with nested JSON key-value objects) in MongoDB
我有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集合中)
您試圖從字符串(實際上是數組)創建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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.