首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用mongodb Java驱动程序更新旧文档?

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

Stack Overflow用户
提问于 2018-08-15 22:15:35
回答 1查看 129关注 0票数 0

我正在尝试实现在mongoDB中检查现有文档,然后我需要使用Java driver 3.4更新它(它不仅仅是旧文档的副本)。

我的代码片段是:

代码语言:javascript
复制
 // 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();
        }

但通过这种方式,我只添加了新文档而不更新。(据我所知,当集群在overflow "document size“__期间自动检查并删除旧文档时,这是很好的。)

当我试图通过添加check in else条件来更新旧文档时:

代码语言:javascript
复制
  // 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();
        }

我得到了:

代码语言:javascript
复制
WARNING: Unsupported option 'retrywrites' in the connection string

更新:

如果我用count方法写else if条件来检查文档数:

代码语言:javascript
复制
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

代码语言:javascript
复制
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.

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

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51877204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档