我正在尝试实现检查 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(); }
2 回答
![?](http://img1.sycdn.imooc.com/545847d40001cbef02200220-100-100.jpg)
小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
有几种方法可以实现它:
上限集合自动删除集合中最旧的文档,而无需脚本或显式删除操作。
使用replaceOne()方法。
要替换文档,请将新文档传递给 replaceOne 方法。
使用updateOne / updateMany方法。就我而言,我只需要更新几个字段,所以我这样写:
collection.updateOne(eq("_id", user_id), new Document("$set", new Document("View links", "On")));
在某些情况下,您可能需要更新文档中的许多字段,替换文档可能更有效。
添加回答
举报
0/150
提交
取消