Java MongoDB驱动程序:如何更新集合中的所有文档?

huangapple go评论72阅读模式
英文:

Java MongoDB driver: How to update all Documents in Collection?

问题

以下代码允许我们更新customerDetail集合中customer_user_id1的所有文档:

db.getCollection("customerDetail")
        .updateMany(Filters.eq("customer_user_id", 1),
                Updates.combine(
                        Updates.set("birth_year", "birth_year"),
                        Updates.set("country", "country")
                ));

但是我需要更新所有集合中的文档,因此我需要找到一种方法来告诉Java驱动程序不要对更新查询应用任何过滤器,但我可以看到updateMany方法中Filter是一个必需的属性,我不能只传递null

那么我如何更新所有文档呢?

英文:

The following code allows us to update all documents in customerDetail collection where customer_user_id is 1:

db.getCollection("customerDetail")
        .updateMany(Filters.eq("customer_user_id", 1),
                Updates.combine(
                        Updates.set("birth_year", "birth_year"),
                        Updates.set("country", "country")
                ));

but I need to update ALL documents in the collection, so I need to find a way how to ask Java Driver do not apply any filters to update query, but as I can see for updateMany method Filter is a mandatory attribute and I can't just pass null.

So how can I update all documents?

答案1

得分: 4

一个我经常使用的选项:

mongoCollectionObject
        .updateMany(new Document(), //
                new Document("$set",
                        new Document("birth_year", "birth_year")
                                .append("country", "country")
                ));

第一个是条件 - 因为空白等同于 {} - 意味着所有文档。

第二个是要设置给所有匹配文档的文档。

英文:

One option which I use frequently

mongoCollectionObject
        .updateMany(new Document(), //
                new Document("$set"
                        new Document("birth_year", "birth_year")
                        .append("country", "country")
                ));

First one is the condition - as it is empty - equivalent to {} - means all documents

second one is the document to be set for all matching documents

huangapple
  • 本文由 发表于 2020年8月6日 21:23:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63284575.html
匿名

发表评论

匿名网友

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

确定