我正在尝试实现在mongoDB中检查现有文档,然后我需要使用Java driver 3.4更新它(它不仅仅是旧文档的副本)。
我的代码片段是:
// 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();
}
但通过这种方式,我只添加了新文档而不更新。(据我所知,当集群在overflow "document size“__期间自动检查并删除旧文档时,这是很好的。)
当我试图通过添加check in else条件来更新旧文档时:
// 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
更新:
如果我用count
方法写else if
条件来检查文档数:
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.
有谁知道如何编写检查文档来更新它们,如果它们已经存在的话?
https://stackoverflow.com/questions/51877204
复制相似问题