在将数组值插入 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 中的 Items 类,并将此类的对象插入到 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));但它没有用。我搜索了很多,有很多例子,但我不知道该怎么做。有什么建议吗?
添加回答
举报
0/150
提交
取消