如何使用Java向现有的MongoDB文档中的数组添加另一个值?

huangapple 未分类评论48阅读模式
标题翻译

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(&quot;Currency&quot;, &quot;Bitcoin&quot;).append(&quot;Values&quot;, Arrays.asList());
//bitCoinCollection.insertOne(bitcoin);

for(int i = 0; i&lt;100;i++){
    BasicDBObject setNewFieldQuery = new BasicDBObject()
                    .append(&quot;$set&quot;, new BasicDBObject().append(&quot;value&quot;, 100));
    mongoClient.getDatabase(&quot;Binance&quot;).getCollection(&quot;Binance&quot;)
               .updateOne(new BasicDBObject().append(&quot;_id&quot;, &quot;tjena&quot;), 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: [ &quot;orange&quot;, &quot;banana&quot; ] }

The following Java code adds one new element to the fruits array:

Bson update = push(&quot;fruits&quot;, &quot;guava&quot;);
Bson filter = eq(&quot;_id&quot;, new Integer(1));
UpdateResult result = collection.updateOne(filter, update);

To add multiple elements all at once from a List collection:

Bson update = pushEach(&quot;fruits&quot;, Arrays.asList(&quot;grape&quot;, &quot;apple&quot;, &quot;peach&quot;));
Bson filter = eq(&quot;_id&quot;, new Integer(1));
UpdateResult result = collection.updateOne(filter, update);

huangapple
  • 本文由 发表于 2020年3月17日 03:44:11
  • 转载请务必保留本文链接:https://java.coder-hub.com/60712303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定