如何在BasicDBObject中插入/放置一个json数组

时间:2015-07-31 07:46:56

标签: java arrays json mongodb bson

我正在使用mongo db driver 2.11.2。我有点困惑如何插入/添加一个数组到BasicDBObject。我遇到的所有示例都没有显示如何实现这一点:(。在下面的示例中,我将如何在dbo对象中插入employees数组?

 /*
    {
    "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());

}

1 个答案:

答案 0 :(得分:1)

使用Arrays.asList作为列表的构造函数。这只是一个清单。而.append()对象键而不是“put”。同样,它就像HashMap接口:

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