mongodb - 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)
)
有谁知道有什么方法可以做到这一点?
解决方案
我不知道这是否是“最好”的方法,但是对于我开始的休息网络服务,我一直在尝试在内部简化 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,但到目前为止它工作得很好。
推荐阅读
- c - 为什么release模式和debug模式的执行结果差别很大?
- mysql - 无法附加 json 数据
- performance - 同一表中不同列的Linq内连接
- ruby-on-rails - 看到帖子反向关系Rails
- python - Tensorflow 如何调度 GPU 操作?使用 TF 时正确的 GPU 调度心智模型是什么?
- python - 如何自动触发 Python 代码?
- ios - facebook发送游戏请求成功,但好友没有收到请求
- angular - Angular 5 无法显示 iFrame
- objectbox - 是 io.objectbox.Box 中的“query()”“put()”“remove()”
线程安全吗? - php - 如何使用 foreach 在数据库中插入 json 数组?