Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert JSON Array into mongodb

Tags:

java

json

mongodb

I'm trying to insert a string that represents a JSON array into a mongodb collection with this,

String str = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"},{\"id\":3,\"data\":\"data3\"}]";
DBObject dbObject = (DBObject) JSON.parse(str);
collection.insert(dbObject);

But I get the exception,

Exception in thread "main" java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]

Can anyone show me the correct way to do this?

like image 483
noob Avatar asked Jan 26 '15 13:01

noob


2 Answers

String json = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"},{\"id\":3,\"data\":\"data3\"}]";
    MongoCredential credential = MongoCredential.createCredential("root", "sample", "root".toCharArray());
    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credential));
    MongoDatabase db = mongoClient.getDatabase("sample");
    MongoCollection<Document> collection = db.getCollection("loginTracking");
    List<Document> jsonList = new ArrayList<Document>();
    net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(json);
    for (Object object : array) {
        net.sf.json.JSONObject jsonStr = (net.sf.json.JSONObject) JSONSerializer.toJSON(object);
        Document jsnObject = Document.parse(jsonStr.toString());
        jsonList.add(jsnObject);

    }
    collection.insertMany(jsonList);
    mongoClient.close();
like image 80
user3041121 Avatar answered Sep 27 '22 19:09

user3041121


as per java doc the insert() can accept either single DBObject or an array or List of them.

So, in order to save, you need to convert your JSON array into an array/List of DBObjects, or save each array's item

like image 21
injecteer Avatar answered Sep 27 '22 20:09

injecteer