Search code examples
javamongodbmongo-java

Is it possible to populate additional fields with a json object for Mongo java?


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]]
    }]
}]}

Solution

  • 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