Mongodb Java 驱动程序将数组插入 Collection

Mongodb Java Driver Insert Array to Collection

我在向 MongoDB 中现有的 collection 插入数组值时遇到了一点问题。我有一个 collection 如下 ;

{ "_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" }

我需要的是将 "images" 标签的值更改为数组值,如下所示;

 "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 中的项目 class 和此 class 的 objects 插入到 MongoDB 中,如下所示;

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

但是没有用。我搜索了很多,有很多例子,但我不知道该怎么做。有什么建议吗?

谢谢

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

String images;

改为

List<String> images;