Skip to main content
 首页 » 编程设计

mongodb中Spring响应式mongodb模板部分使用对象更新文档

2025年12月25日34lori

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

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

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

比方说,我的 Foo 类包含上述所有这些字段。

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

{ 
   "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 方法,并且我使用 Map 来实现使用 org.apache.commons.beanutils.PropertyUtils 库,然后创建要传递给 ReactiveMongoTemplate 的 Update 对象,或多或少像这样:

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,但到目前为止它运行得很好。