1.使用MongoTemplate
a.批量插入
Insert a Collection of objects into a collection in a single batch write to the database.
<T> Collection<T> insert(Collection<? extends T> batchToSave, Class<?> entityClass);
或Insert a batch of objects into the specified collection in a single batch write to the database.
<T> Collection<T> insert(Collection<? extends T> batchToSave, String collectionName);
或 Insert a mixed Collection of objects into a database collection determining the collection name to use based on the
class.(將混合的對象集合插入數據庫集合中,根據類確定要使用的集合名稱。)
<T> Collection<T> insertAll(Collection<? extends T> objectsToSave);
b.批量更新
Updates all objects that are found in the collection for the entity class that matches the query document criteria
with the provided updated document.
UpdateResult updateMulti(Query query, Update update, Class<?> entityClass);
或
Updates all objects that are found in the specified collection that matches the query document criteria with the
provided updated document.
UpdateResult updateMulti(Query query, Update update, String collectionName);
或
Updates all objects that are found in the collection for the entity class that matches the query document criteria
with the provided updated document.
UpdateResult updateMulti(Query query, Update update, Class<?> entityClass, String collectionName);
c.批量刪除
Remove all documents that match the provided query document criteria from the the collection used to store the
entityClass. The Class parameter is also used to help convert the Id of the object if it is present in the query.
DeleteResult remove(Query query, Class<?> entityClass);
DeleteResult remove(Query query, Class<?> entityClass, String collectionName);
DeleteResult remove(Query query, String collectionName);
d.查找並刪除
<T> List<T> findAllAndRemove(Query query, String collectionName);
<T> List<T> findAllAndRemove(Query query, Class<T> entityClass);
<T> List<T> findAllAndRemove(Query query, Class<T> entityClass, String collectionName);
2.還有其他批量操作的方式。例如基於BulkOperations的操作
使用形式:
例:BulkOperations bulkOp = this.template.bulkOps(BulkMode.UNORDERED, COLLECTION_NAME);
獲取BulkOperations對象后,在進行批量操作,具體查看BulkOperations提供的方法。
最后,execute()執行。
public Integer batchInsertDetailCommonDailyMessages(List<DetailCommonDailyStatis> messages) { if (CollectionUtils.isEmpty(messages)) { return 0; } // 插入新數據 BulkOperations bulkOp = this.template.bulkOps(BulkMode.UNORDERED, COLLECTION_NAME); //BulkNode有兩種形式 bulkOp.insert(messages); BulkWriteResult result = bulkOp.execute();int insertCount = result.getInsertedCount();return insertCount; }
3.基於MongoRepository