Spring Data MongoDB将数组添加到现有文档 [英] Spring data MongoDB adding arrays to an existing document
问题描述
说我有以下收藏
public @Data class Customer {
@Id
private String id;
private String firstName;
private String lastName;
@DBRef
private List<Address> addressList= new ArrayList<Address>();
}
和
public @Data class Address {
@Id
private String id;
private String address;
private String type;
private String customerID;
}
每个客户都有多个地址,我已经实现了MongoRepository
.第一次保存客户在customerRepo.save(customerObject)
上运行良好,在调用保存之前,我先保存多个地址对象,然后将其设置为addressList
.
下次当我更新同一文档并想向现有列表中添加一组新的地址时,它将覆盖整个addressList
数组.因此,基本上,如果有数千个(或超过一千个)元素,或者现在我要对addressList数组进行切片,那么现在要做的就是像这样existingCustomerObject.getAddressList().addAll(my new List of address)
设置新地址,以下过程将不是一个好主意.我的问题是实现此方案的最佳方法是什么?说出我是否不想使用MongoTemplate
.是否可以仅使用MongoRepository
And each Customer has multiple addresses, and I have implemented MongoRepository
. Saving customer for the First time is working pretty well customerRepo.save(customerObject)
and before calling the save I am persisting multiple Address Objects and then setting those to the addressList
.
Next time when I am updating the same document and want to add a New set of Address to the existing list it is overwriting the whole addressList
array. So basically what I have to do now to set new address like thisexistingCustomerObject.getAddressList().addAll(my new List of address)
if there are thousand(or more than thousand) of elements or I am slicing the addressList array the following procedure won't be a good idea. My question is what is the best way to achieve this scenario? say if I don't want to use MongoTemplate
. Is it possible Just using the MongoRepository
推荐答案
我认为您无法以这种方式进行操作.以前我也有同样的情况,我尝试了以下方法
I don't think you can do it in that way. Previously i had the same situation, and I tried the following
1. org.springframework.core.convert.converter.Converter
即使我设法操纵D BObject
,但$push
或$set
(将它们包裹在键下)之类的功能也无法在那儿工作.
1.org.springframework.core.convert.converter.Converter
even I have managed to manipulate the DBObject
but functions like $push
or $set
(wrapping them under key) does not work over there.
2. AbstractMongoEventListener
通过覆盖onBeforeSave
,但是在保存期间未进行对象操作.
2.AbstractMongoEventListener
by overriding onBeforeSave
but Object manipulation was not taking place during save.
但是您可以尝试更改提到的内容
However you can try altering the mentioned
您可以尝试覆盖MongoRepository
保存方法,如果有人指向正确的方向,效果会更好.
否则,对于我的情况,我必须创建与MongoRepository
并行工作(用于插入和检索数据/文档)的自定义存储库(以更新和删除文档),但是我认为这是一个丑陋的解决方法.必须有一种更清洁的方式来做到这一点.
you can try override MongoRepository
save method, It would better if someone point to the right direction.
Otherwise for my scenario I had to create Custom repository(To update and delete document) which is working parallel with MongoRepository
(for Insert and retrieve data/document), but I believe thats an ugly workaround. There has to be a cleaner way to do it.
这篇关于Spring Data MongoDB将数组添加到现有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!