【问题标题】:Java MongoDB driver: How to update all Documents in Collection?Java MongoDB 驱动程序:如何更新集合中的所有文档?
【发布时间】:2020-08-06 13:23:51
【问题描述】:

以下代码允许我们更新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")
                ));

但我需要更新集合中的 ALL 文档,所以我需要找到一种方法来要求 Java 驱动程序不要应用任何过滤器来更新查询,但正如我看到的 @987654325 @方法Filter是强制属性,我不能只传递null

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

【问题讨论】:

  • 为什么不发送new Document() 作为第一个参数?

标签: java mongodb mongo-java-driver


【解决方案1】:

我经常使用的一个选项

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

第一个是条件 - 因为它是空的 - 相当于 {} - 表示所有文档

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多