Search code examples
javaarraysjsonmongodbbson

how to insert/put a json array in the BasicDBObject


I am using mongo db driver 2.11.2. I am bit puzzled how to insert/add an array to the BasicDBObject. All the example which I come across are does not show how to achieve this :(. In the below example how would I insert employees array in the dbo object ?

 /*
    {
    "company" : "stackoverflow",
    "established": "when I started coding"
    "employees":[
        {"firstName":"John", "lastName":"Doe"},
        {"firstName":"Anna", "lastName":"Smith"},
        {"firstName":"Peter", "lastName":"Jones"}
       ]
    }
     */

    BasicDBObject basicDBObject = new BasicDBObject();
    basicDBObject.put("company", "stackoverflow");
    basicDBObject.put("established", "when I started coding");
    System.out.println(basicDBObject.toString());

}

Solution

  • Use the Arrays.asList as a contructor for the list. It's just a list. And .append() the object keys rather than "put". Again, it's just as HashMap interface:

        BasicDBObject basicDBObject = new BasicDBObject();
        basicDBObject.put("company", "stackoverflow");
        basicDBObject.append("established", "when I started coding");
        basicDBObject.append("employees", Arrays.<DBObject>asList(
            new BasicDBObject("firstName", "john")
                .append("lastName", "doe"),
            new BasicDBObject("firstName", "anna")
                .append("lastName", "smith"),
            new BasicDBObject("firstName", "peter")
                .append("lastName", "jones")
        ));
        System.out.println(basicDBObject.toString());