首页 > 解决方案 > 如何使用 mongodb Java 驱动程序更新旧文档?

问题描述

我正在尝试使用 Java 驱动程序 3.4来检查 mongoDB 中的现有文档,然后我需要对其进行更新(它不只是复制旧文档) 。

我的代码片段是:

 // 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();
        }

但是通过这种方式,我只是添加了新文档而不进行更新。 (据我了解,这很好,当集群将在溢出“文档大小”期间检查自身并在没有我的情况下删除旧文档时)

当我尝试通过添加签入其他条件来更新旧文档时:

  // 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

在此处输入图像描述


更新:

如果我用检查文件数量的方法编写else if条件:count

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.

有谁知道如何编写检查文件来更新它们,如果它们存在的话?

标签: java

解决方案


retryWritesMongoDb 3.6中根据this添加了connection参数。正如您自己所说,您使用的是 3.4 版,因此发出警告。

在您的代码中的某处,您可能有一个类似于以下内容的连接字符串mongodb://db1.example.net:27017?retryWrites=true:您要么需要升级到 >= 3.6 的版本,要么retryWrites从连接字符串中删除参数以消除警告。


推荐阅读