MongoDB Java驱动程序插入阵列到收集



我有一个小问题,同时将数组值插入MongoDB中的现有集合。我有下面的集合;

{ "_id" : "1", "username" : "", "password" : "!", "firm" : "SpringSource", "roles" : [ "admin", "client" ], "items" : [ { "_id" : "1b7cb58b-dc5b-4d27-9402-d43d3844d11d", "id" : 1, "title" : "Coffee", "price" : "12", "category" : "Coffee", "images" : "Obj1", "description" : "Coffee" } ], "latitude" : "39.877619", "longitude" : "32.682537" }

我需要的是将"图像"标签的值更改为以下数组值;

 "items" : [ { "_id" : "1b7cb58b-dc5b-4d27-9402-d43d3844d11d", "id" : 1, "title" : "Coffee", "price" : "12", "category" : "Coffee", "images" : ["Obj1","Obj2"], "description" : "Coffee" } ], "latitude" : "39.877619", "longitude" : "32.682537" }

我在Java中有项目类,此类的对象如下;

    Item item= new Item(id,title,price,category,image,description);
    //String all=item.toString();
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(item);
    Document doc = Document.parse( json.toString() );
    db.getCollection("users").updateOne(new Document("username",uname1),
            new Document("$push", new Document("items", doc)));

它可以按预期工作,但如上所述,我需要将图像作为数组存储。我在下面尝试了一些;

List<String> topics = new ArrayList<String>();
topics.add("Obj1");
topics.add("Obj2");

col.findOneAndUpdate(Filters.eq("_id", new.    ObjectId("58b1404d002d2b1a481b8ddf")), Updates.pushEach("images",    topics));

,但它行不通。我已经搜索了很多例子,但我不知道该怎么做。有任何建议吗?

thanx

最简单的想法是更改Item类,而不是

String images;

更改为

List<String> images;