首页 > 解决方案 > Spring响应式mongodb模板更新文档部分包含对象

问题描述

我有一些类(文档)要在 mongo db 中更新

mongo中存储的文档(实际例子比较复杂):

{
   "id": "5ba6b0576cba836aa43ab379",
   "firstName": "First Name",
   "lastName": "Last Name",
   "mobile": "123456789"
   ....................
   ....................
   ....................
   "address": "some address"
}

假设,我有上面所有这些字段的类 Foo 。

我从外部部分对象接收(Foo 只有 3 个值,所有其他值都为空),例如:

{
   "id": "5ba6b0576cba836aa43ab379",
   "mobile": "987654321",
   "address": "other address"
}

我想更新文档,但只包含收到的字段。

我发现只有使用 reactivemongotemplate 手动执行此操作的选项。我正在寻找更“好”的方式,而无需手动创建更新对象。就像是:

reactivemongotemplate.updateFirst(
    Query.query(Criteria.where("id").is("5ba6b0576cba836aa43ab379")), 
    partialFoo // (object of class is Foo)
)

有谁知道有什么方法可以做到这一点?

标签: mongodbspring-bootspring-data

解决方案


我不知道这是否是“最好”的方法,但是对于我开始的休息网络服务,我一直在尝试在内部简化 PATCH 和 PUT 方法,我使用使用org.apache.commons.beanutils.PropertyUtils库的 Map 来做到这一点然后我创建要传递给的 Update 对象ReactiveMongoTemplate,或多或少像这样:

Map<String, Object> changes = PropertyUtils.describe(myDto);
// ... check the fields that must be sets and other business rules ...
Update updateFields = new Update();
for(Map.Entry<String, Object> entry : changes.entrySet()){
  updateFields.set(entry.getKey(), entry.getValue());
}
reactivemongotemplate.updateFirst(query(where("id").is(myId)), updateFields, MyEntity.class)

这意味着您的MyDto类对于您需要的每个字段都有 getter 和 setter,但到目前为止它工作得很好。


推荐阅读