我正在尝试实现检查 mongoDB 中的现有文档,然后我需要使用 Java 驱动程序 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();
}
但是通过这种方式,我只是添加了新文档而不进行更新。 (据我所知,这很好,当集群将在溢出“文档大小”期间检查自身并删除旧文档时不会删除旧文档)
当我尝试通过添加签入 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();
}
小怪兽爱吃肉
相关分类