2

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

}
2
  • 2
    Check Here: stackoverflow.com/questions/7852809/… Commented Jul 31, 2015 at 7:49
  • AKS you are awesome , struggling for this for couple of hours Commented Jul 31, 2015 at 7:58

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

3 Comments

just for the info, you have missed an comma after "smith"
@rockyit86 Cut and paste bites me every time. Did not have an IDE open and just typed in here.
no worries , I cannot type anything without an IDE , such a poor typist, and I guess I am not alone :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.