如何使用 mongodb Java 驱动程序更新旧文档?

我正在尝试实现检查 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();

        }


开心每一天1111
浏览 156回答 2
2回答

小怪兽爱吃肉

有几种方法可以实现它:使用上限集合。上限集合自动删除集合中最旧的文档,而无需脚本或显式删除操作。使用replaceOne()方法。要替换文档,请将新文档传递给 replaceOne 方法。使用updateOne / updateMany方法。就我而言,我只需要更新几个字段,所以我这样写:collection.updateOne(eq("_id", user_id), new Document("$set", new Document("View links", "On")));在某些情况下,您可能需要更新文档中的许多字段,替换文档可能更有效。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java