以下代码允许我们更新 customerDetail
集合中 customer_user_id
为 1
的所有文档:
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
。
那么如何更新所有文档呢?
最佳答案
我经常使用的一个选项
mongoCollectionObject
.updateMany(new Document(), //
new Document("$set"
new Document("birth_year", "birth_year")
.append("country", "country")
));
第一个是条件 - 因为它是空的 - 相当于 {}
- 表示所有文档
第二个是要为所有匹配文档设置的文档
关于Java MongoDB 驱动程序 : How to update all Documents in Collection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63284575/