java - 如何使用 mongodb Java 驱动程序更新旧文档?
问题描述
我正在尝试使用 Java 驱动程序 3.4来检查 mongoDB 中的现有文档,然后我需要对其进行更新(它不只是复制旧文档) 。
我的代码片段是:
// search feed
Document found = database.getCollection("rss_feed").find(new Document("title", title)
.append("url", url)
.append("img", img)
.append("price", price)).first();
if (found == null) {
collection.insertOne(new Document("title", title)
.append("url", url)
.append("img", img)
.append("price", price));
mongoClient.close();
System.out.println("Feed not exists in database. Written.");
} else {
System.out.println("Feed exists in database.");
mongoClient.close();
}
但是通过这种方式,我只是添加了新文档而不进行更新。 (据我了解,这很好,当集群将在溢出“文档大小”期间检查自身并在没有我的情况下删除旧文档时)
当我尝试通过添加签入其他条件来更新旧文档时:
// search feed
Document found = database.getCollection("rss_feed").find(new Document("title", title)
.append("url", url)
.append("img", img)
.append("price", price)).first();
if (found == null) {
collection.insertOne(new Document("title", title)
.append("url", url)
.append("img", img)
.append("price", price));
mongoClient.close();
System.out.println("Feed not exists in database. Written.");
} else {
collection.updateOne(eq(found), new Document("title", title)
.append("url", url)
.append("img", img)
.append("price", price));
mongoClient.close();
System.out.println("Feed exists in database. Updated");
mongoClient.close();
}
我越来越:
WARNING: Unsupported option 'retrywrites' in the connection string
更新:
如果我用检查文件数量的方法编写else if
条件:count
else if(collection.count() > 36) {
collection.updateOne(found, new Document("updated title", title)
.append("updated url", url)
.append("updated img", img)
.append("updated price", price));
System.out.println("Feed completely updated in database.");
然后else if
将被跳过:
Feed already exists in database.
Feed already exists in database.
Feed already exists in database.
Feed already exists in database.
Feed already exists in database.
有谁知道如何编写检查文件来更新它们,如果它们存在的话?
解决方案
retryWrites
MongoDb 3.6中根据this添加了connection参数。正如您自己所说,您使用的是 3.4 版,因此发出警告。
在您的代码中的某处,您可能有一个类似于以下内容的连接字符串mongodb://db1.example.net:27017?retryWrites=true
:您要么需要升级到 >= 3.6 的版本,要么retryWrites
从连接字符串中删除参数以消除警告。
推荐阅读
- javascript - 使用 axios 查看原始请求响应头
- python - PyQt5 线程无响应
- c++ - 日志函数返回不正确的值
- angular - 如何使用 jsPDF 呈现多个分页结果(HTML 到 PDF)
- python - 打印 M x N 网格,每个网格内都有字符
- wpf - WPF 从主窗口获取命令行参数到视图模型中
- android - 如何在 Android 中通过字符串或文件名确定主要媒体类型?
- javascript - 如何使用反应钩子创建反应多步模态表单
- bpy - BPY - 如何创建一个布尔标志来检查按钮是否被点击?
- python - Pandas newbie - 阅读 excel - 尝试将公式应用于列