为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

开心每一天1111 2021-07-20 17:01:15
我正在尝试实现检查 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 回答

?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

有几种方法可以实现它:

  1. 使用上限集合

上限集合自动删除集合中最旧的文档,而无需脚本或显式删除操作。

  1. 使用replaceOne()方法。

要替换文档,请将新文档传递给 replaceOne 方法。

  1. 使用updateOne / updateMany方法。就我而言,我只需要更新几个字段,所以我这样写:

    collection.updateOne(eq("_id", user_id), new Document("$set", new Document("View links", "On")));

在某些情况下,您可能需要更新文档中的许多字段,替换文档可能更有效。


查看完整回答
反对 回复 2021-07-23
  • 2 回答
  • 0 关注
  • 155 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信