标题翻译
How do i add another value to an array in an existing MongoDB document using Java?
问题
这是我的当前代码
Document bitcoin = new Document("Currency", "Bitcoin").append("Values", Arrays.asList());
//bitCoinCollection.insertOne(bitcoin);
for(int i = 0; i<100; i++){
BasicDBObject setNewFieldQuery = new BasicDBObject()
.append("$set", new BasicDBObject().append("value", 100));
mongoClient.getDatabase("Binance").getCollection("Binance")
.updateOne(new BasicDBObject().append("_id", "tjena"), setNewFieldQuery);
}
它没有向现有的ArrayList添加任何值... 是否有办法将其添加到文档中的现有ArrayList?提前谢谢。
英文翻译
This is my current code
Document bitcoin = new Document("Currency", "Bitcoin").append("Values", Arrays.asList());
//bitCoinCollection.insertOne(bitcoin);
for(int i = 0; i<100;i++){
BasicDBObject setNewFieldQuery = new BasicDBObject()
.append("$set", new BasicDBObject().append("value", 100));
mongoClient.getDatabase("Binance").getCollection("Binance")
.updateOne(new BasicDBObject().append("_id", "tjena"), setNewFieldQuery);
}
It doesnt add any values to the excisting arraylist... is there a way to add it to an excisting arraylist in a document? Thanks in advance
答案1
得分: 0
对于使用MongoDB Java驱动程序的一个带有数组字段的文档样本集合:
{ _id: 1, fruits: [ "orange", "banana" ] }
以下是Java代码,它将一个新元素添加到fruits
数组中:
Bson update = push("fruits", "guava");
Bson filter = eq("_id", new Integer(1));
UpdateResult result = collection.updateOne(filter, update);
要一次性从List
集合中添加多个元素:
Bson update = pushEach("fruits", Arrays.asList("grape", "apple", "peach"));
Bson filter = eq("_id", new Integer(1));
UpdateResult result = collection.updateOne(filter, update);
英文翻译
For this sample collection of one document with an array field using MongoDB Java driver:
{ _id: 1, fruits: [ "orange", "banana" ] }
The following Java code adds one new element to the fruits
array:
Bson update = push("fruits", "guava");
Bson filter = eq("_id", new Integer(1));
UpdateResult result = collection.updateOne(filter, update);
To add multiple elements all at once from a List
collection:
Bson update = pushEach("fruits", Arrays.asList("grape", "apple", "peach"));
Bson filter = eq("_id", new Integer(1));
UpdateResult result = collection.updateOne(filter, update);
专注分享java语言的经验与见解,让所有开发者获益!
评论