mongodb 批量添加、修改和删除

时间:2019-10-30
本文章向大家介绍mongodb 批量添加、修改和删除,主要包括mongodb 批量添加、修改和删除使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

原文地址:https://www.cnblogs.com/muxi0407/p/11765140.html