noob
noob

Reputation: 148

Insert JSON Array into 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?

Upvotes: 7

Views: 15369

Answers (3)

Valfar Developer
Valfar Developer

Reputation: 340

I found a good way for achieve that:

(ArrayList<Document>) JSON.parse("[String json array]");

I had a problem with this, because i need append to this document a property that is a Json Array:

Document objAddendumVersion = new Document();
objAddendumVersion.append("_id", new ObjectId());
objAddendumVersion.append("Array", My Array here!);

But the problem is that Document.parse() doesn't work with Arrays, so i could solve it using the above line. So the final code is:

Document objAddendumVersion = new Document();
objAddendumVersion.append("_id", new ObjectId());
objAddendumVersion.append("Array", (ArrayList<Document>) JSON.parse("[String json array]"));

And it works perfect. Yes i know that exist more better ways for do that, but for the moment i'm using this.

I wait that be useful for someone with the same trouble.

Upvotes: 0

user3041121
user3041121

Reputation: 61

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();

Upvotes: 3

injecteer
injecteer

Reputation: 20707

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

Upvotes: 1

Related Questions