在将数组值插入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" }
我需要将“ 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中的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 :(得分:0)
最简单的想法是更改Item
类,而不是
String images;
更改为
List<String> images;