英文:
Java MongoDB driver: How to update all Documents in Collection?
问题
以下代码允许我们更新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
。
那么我如何更新所有文档呢?
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论