我正在嘗試實現(xiàn)檢查 mongoDB 中的現(xiàn)有文檔,然后我需要使用 Java 驅(qū)動程序 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(); }但是通過這種方式,我只是添加了新文檔而不進行更新。 (據(jù)我所知,這很好,當集群將在溢出“文檔大小”期間檢查自身并刪除舊文檔時不會刪除舊文檔)當我嘗試通過添加簽入 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 回答

小怪獸愛吃肉
TA貢獻1852條經(jīng)驗 獲得超1個贊
有幾種方法可以實現(xiàn)它:
上限集合自動刪除集合中最舊的文檔,而無需腳本或顯式刪除操作。
使用replaceOne()方法。
要替換文檔,請將新文檔傳遞給 replaceOne 方法。
使用updateOne / updateMany方法。就我而言,我只需要更新幾個字段,所以我這樣寫:
collection.updateOne(eq("_id", user_id), new Document("$set", new Document("View links", "On")));
在某些情況下,您可能需要更新文檔中的許多字段,替換文檔可能更有效。
添加回答
舉報
0/150
提交
取消