java - 更新 mongoDB

标签 java spring mongodb spring-data-mongodb

我有一个使用 spring 框架的应用程序,并使用 mongoDB 作为数据库。我有一个通过电子邮件索引的集合。这些字段是:

{
    email: <email>
    profile: {
        name: <name>
        age: <age>
        customMap: {
        }
    }
}

这是文档:

@Document(collection = "user")
class User {
    String email;
    Profile profile;
}

class Profile {
    String name;
    int age;
    Map customMap;
}

用例是电子邮件字段是唯一的。因此,当现有电子邮件收到请求时,我需要使用新的个人资料更新文档。我可以使用 mongoOperations.save 插入新文档称呼。但是在进行更新时,如果我使用新 map 传递 customProfile,我会得到

java.lang.IllegalArgumentException: [Assertion failed] - this argument is required; it must not be null

作为一个错误。但如果我尝试仅更新 age字段,更新成功。我仅在使用 map 时遇到问题,并且我正在使用 HashMap

这是更新代码:

Update update = new Update();
Profile profile = new Profile();
profile.setAge(10);
Map customMap = new HashMap();
customMap.put("name", "value");
profile.setCustomMap(customMap);
update.set("profile", profile);
mongoOperations.updateFirst(query, update, User.class);

如果我注释掉profile.setCustomMap(customMap);然后就更新成功了。我在这里遗漏了什么吗?

最佳答案

确保在您的用户对象中设置电子邮件。否则数据库将不知道要更新哪个用户。

关于java - 更新 mongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23513180/

相关文章:

java - 与 Android 操作系统类似,对 JVM 内存消耗进行基准测试

java - 启用 WiFi 后,广播接收器能否收到移动数据 CONNECTIVITY_CHANGE 通知?

java - 如何在while循环中使用String方法

java - 在 DAO 实现类中实现默认的 JPA findAll 方法

java - Spring Boot带附件的邮件发送

node.js - 如何使用 Node js从mongodb中的3个集合中获取数据?

python - 使用pymongo连接到aws时出现ServerSelectionTimeoutError

java - Apache POI 依赖项

c# - 来自 Spring 上下文的进度条?

mongodb - 如何在mongodb中级联删除文档?