0

I know there is a BasicDBObject that allows you do go:

BasicDBObject info = new BasicDBObject();

info.put("x", 203);
info.put("y", 102);

The issue I have is that the value can only be a primitive type. I have a json object that I want to store with the common data that I am unable to modify, but would like to describe json object in a single mongo document. What can I do in order to do something like:

BasicDBObject info = new BasicDBObject();
info.put("Name", "John");
info.put("Main Hobby", "Hiking");
info.put("Albums", json-string-with-nested-arrays);

To sum up, I am looking for a way to allow me to store both a json object in addition to key value pairs in the same document (assume that the "json-string-with-nested-arrays" I have is not modifiable, so I cannot insert additional attributes into it.) How can I accomplish this?

Below is the json-string-with-nested-arrays:

{"data":[{"stuff":[
    {"onetype":[
        {"id":1,"name":"John Doe"},
        {"id":2,"name":"Don Joeh"}
    ]},
    {"othertype":[
        {"id":2,"company":"ACME"}
    ]}]
},{"otherstuff":[
    {"thing":
        [[1,42],[2,2]]
    }]
}]}
Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
Rolando
  • 58,640
  • 98
  • 266
  • 407

1 Answers1

1

If "json-string-with-nested-arrays" is a JSON string then you can do something like this in mongo-java-driver.

info.put("Albums", JSON.parse(json-string-with-nested-arrays));

This JSON.parse() method is part of mongo-java-driver

Ravi Khakhkhar
  • 1,924
  • 1
  • 18
  • 25
  • json-string-with-nested-arrays has to be perfectly formatted Json String – Ravi Khakhkhar Jun 20 '12 at 04:00
  • Not functioning correctly as it only stores the JSON object as a string and not a JSON object. – Rolando Jun 20 '12 at 04:17
  • I don't thinks so. JSON.parse() method converts JSON String to mongo compatible JSON. I could not get how come this can happen.I'm able to use this perfectly fine – Ravi Khakhkhar Jun 20 '12 at 04:21
  • If you do an ajax call using jsonp or json, you will notice that the value for the key "Albums" is a string(of the json object). – Rolando Jun 20 '12 at 04:27
  • Can you show me the your `json-string-with-nested-arrays`? And what's the `Accept` request header when you make Ajax call – Ravi Khakhkhar Jun 20 '12 at 04:37
  • Client-Side ajax call accept: jsonp, headers application-x/javascript. I have added the json-string-with-nested-arrays to my original post. – Rolando Jun 20 '12 at 04:39
  • are you sure json-string-with-nested-arrays is `instaceof` string ?? – Ravi Khakhkhar Jun 20 '12 at 05:42
  • http://www.mkyong.com/mongodb/java-mongodb-insert-a-document/ and see section **JSON parse example**, you will realize how this works. – Ravi Khakhkhar Jun 20 '12 at 05:53