我有一个像
这样的记录列表[
{"id":"1", "name":"a", "user":"u1"},
{"id":"2", "name":"b", "user":"u1"},
{"id":"3", "name":"c", "user":"u1"}
]
现在根据条目是否已存在于数据库中,它应该更新或插入文档。此外,对于更新,存在一个条件,即现有 user
字段的值应与文档中为 user
提供的值相匹配。
当然我可以循环运行列表并使用
mongoOperations.save(...);
但是,如果我有一个巨大的列表,那么我将不得不为每个条目执行一个数据库操作,我认为这效率不高。有没有其他有效的方法来执行此操作?
最佳答案
如果您使用的是 CRUD 存储库,则 CRUD 存储库提供了可用于单个实体(mongoCollection)的 save() 方法,或者您可以使用重载的 save 方法
<S extends T> List<S> saveAll(Iterable<S> entites)
可以取Arraylist并保存arraylist对象。无需使用循环。
您可以看到下面的示例,其中 InventoryService 类创建了 3 个库存对象并将所有对象添加到 ArrayList 中,最后将其传递给库存存储库,这是一个 CRUD 存储库。
@Service
public class InventoryService {
private static final Logger LOGGER = LoggerFactory.getLogger(InventoryService.class);
@Autowired
private InventoryRepository inventoryRepository;
public void aveInventoryDetails() {
List<Inventory> inventoryList = new ArrayList<Inventory>();
inventoryList.add(new Inventory("500", 10));
inventoryList.add(new Inventory("600", 20));
inventoryList.add(new Inventory("700", 30));
try {
inventoryRepository.saveAll(inventoryList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例 Mongo 存储库
package com.bjs.repository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.bjs.model.Inventory;
public interface InventoryRepository extends MongoRepository<Inventory, String> {
// empty as not defining any new method , we can use the existing save method
}
关于spring mongodb 添加或更新文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43299954/