springboot集成 mongodb以及mongodb简单工具类

前言

springboot集成 mongodb 有开箱即用的starter 因此集成还是很方便的

集成

  • 添加依赖
xml 复制代码
  <!--mongodb-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • 添加配置
properties 复制代码
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydatabase

使用

直接注入

java 复制代码
@Autowired
 private MongoTemplate mongoTemplate;

封装的简单工具类

复制代码
public interface MongoRepository {

    MongoOperations getMongoTemplate();

    /**
     * 获取集合
     *
     * @param collectionName 集合
     * @return MongoCollection
     */

    MongoCollection<Document> getCollection(String collectionName);


    MongoCollection<Document> getCollection(Query query, String collectionName);

    /**
     * 插入
     *
     * @param collectionName collectionName
     * @param doc            doc
     */
    void insert(String collectionName, Document doc);

    /**
     * 更新文档
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @param updateDoc      文档
     * @return long
     */
    long update(String collectionName, Bson filter, Document updateDoc);

    /**
     * 统计
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @return long
     */
    long count(String collectionName, Bson filter);

    /**
     * 统计
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @return long
     */
    long countByLimit(String collectionName, Integer limit, Bson filter);

    /**
     * 去重
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @param fieldName      fieldName
     * @return long
     */
    long distinctCount(String collectionName, Bson filter, String fieldName);

    /**
     * 根据指定的管道聚合文档
     *
     * @param collectionName collectionName
     * @param pipeline       pipeline
     * @return AggregateIterable
     */
    AggregateIterable<Document> aggregate(String collectionName, List<Bson> pipeline);

    /**
     * 查找
     *
     * @param collectionName collectionName
     * @param filter         filter
     * @return FindIterable
     */
    FindIterable<Document> find(String collectionName, Bson filter);

    /**
     * 获取实体类对应的集合名称
     *
     * @param entityClass entityClass
     * @return String
     */
    String getCollectionName(Class<?> entityClass);

    //新增api 

    /**
     * Insert the object into the collection for the entity type of the object to save.
     * <br />
     * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}.
     * <br />
     * If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a
     * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your
     * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See
     * <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation" > Spring's
     * Type Conversion"</a> for more details.
     * <br />
     * Insert is used to initially store the object into the database. To update an existing object use the save method.
     * <br />
     * The {@code objectToSave} must not be collection-like.
     *
     * @param objectToSave the object to store in the collection. Must not be {@literal null}.
     * @return the inserted object.
     * @throws IllegalArgumentException                          in case the {@code objectToSave} is collection-like.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} from the given object type.
     */
    <T> T insert(T objectToSave);

    /**
     * Insert the object into the specified collection.
     * <br />
     * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * Insert is used to initially store the object into the database. To update an existing object use the save method.
     * <br />
     * The {@code objectToSave} must not be collection-like.
     *
     * @param objectToSave   the object to store in the collection. Must not be {@literal null}.
     * @param collectionName name of the collection to store the object in. Must not be {@literal null}.
     * @return the inserted object.
     * @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
     */
    <T> T insert(T objectToSave, String collectionName);

    /**
     * Insert a Collection of objects into a collection in a single batch write to the database.
     *
     * @param batchToSave the batch of objects to save. Must not be {@literal null}.
     * @param entityClass class that determines the collection to use. Must not be {@literal null}.
     * @return the inserted objects that.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} from the given type.
     */
    <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.
     *
     * @param batchToSave    the list of objects to save. Must not be {@literal null}.
     * @param collectionName name of the collection to store the object in. Must not be {@literal null}.
     * @return the inserted objects that.
     */
    <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.
     *
     * @param objectsToSave the list of objects to save. Must not be {@literal null}.
     * @return the inserted objects.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} for the given objects.
     */
    <T> Collection<T> insertAll(Collection<? extends T> objectsToSave);

    /**
     * Save the object to the collection for the entity type of the object to save. This will perform an insert if the
     * object is not already present, that is an 'upsert'.
     * <br />
     * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a
     * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your
     * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API. See
     * <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation" > Spring's
     * Type Conversion"</a> for more details.
     * <br />
     * The {@code objectToSave} must not be collection-like.
     *
     * @param objectToSave the object to store in the collection. Must not be {@literal null}.
     * @return the saved object.
     * @throws IllegalArgumentException                          in case the {@code objectToSave} is collection-like.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} from the given object type.
     */
    <T> T save(T objectToSave);

    /**
     * Save the object to the specified collection. This will perform an insert if the object is not already present, that
     * is an 'upsert'.
     * <br />
     * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * If your object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a
     * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your
     * property type will be handled by Spring's BeanWrapper class that leverages Type Conversion API.
     * See <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation">Spring's Type Conversion</a> for more details.
     * <br />
     * The {@code objectToSave} must not be collection-like.
     *
     * @param objectToSave   the object to store in the collection. Must not be {@literal null}.
     * @param collectionName name of the collection to store the object in. Must not be {@literal null}.
     * @return the saved object.
     * @throws IllegalArgumentException in case the {@code objectToSave} is collection-like.
     */
    <T> T save(T objectToSave, String collectionName);

    /**
     * Map the results of an ad-hoc query on the collection for the entity class to a single instance of an object of the
     * specified type.
     * <br />
     * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
     * feature rich {@link Query}.
     *
     * @param query       the query class that specifies the criteria used to find a record and also an optional fields
     *                    specification.
     * @param entityClass the parametrized type of the returned list.
     * @return the converted object.
     */
    @Nullable
    <T> T findOne(Query query, Class<T> entityClass);

    /**
     * Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified
     * type.
     * <br />
     * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
     * feature rich {@link Query}.
     *
     * @param query          the query class that specifies the criteria used to find a record and also an optional fields
     *                       specification.
     * @param entityClass    the parametrized type of the returned list.
     * @param collectionName name of the collection to retrieve the objects from.
     * @return the converted object.
     */
    @Nullable
    <T> T findOne(Query query, Class<T> entityClass, String collectionName);

    /**
     * Determine result of given {@link Query} contains at least one element. <br />
     * <strong>NOTE:</strong> Any additional support for query/field mapping, etc. is not available due to the lack of
     * domain type information. Use {@link #exists(Query, Class, String)} to get full type specific support.
     *
     * @param query          the {@link Query} class that specifies the criteria used to find a record.
     * @param collectionName name of the collection to check for objects.
     * @return {@literal true} if the query yields a result.
     */
    boolean exists(Query query, String collectionName);

    /**
     * Determine result of given {@link Query} contains at least one element.
     *
     * @param query       the {@link Query} class that specifies the criteria used to find a record.
     * @param entityClass the parametrized type.
     * @return {@literal true} if the query yields a result.
     */
    boolean exists(Query query, Class<?> entityClass);

    /**
     * Determine result of given {@link Query} contains at least one element.
     *
     * @param query          the {@link Query} class that specifies the criteria used to find a record.
     * @param entityClass    the parametrized type. Can be {@literal null}.
     * @param collectionName name of the collection to check for objects.
     * @return {@literal true} if the query yields a result.
     */
    boolean exists(Query query, @Nullable Class<?> entityClass, String collectionName);

    /**
     * Map the results of an ad-hoc query on the collection for the entity class to a List of the specified type.
     * <br />
     * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
     * feature rich {@link Query}.
     *
     * @param query       the query class that specifies the criteria used to find a record and also an optional fields
     *                    specification. Must not be {@literal null}.
     * @param entityClass the parametrized type of the returned list. Must not be {@literal null}.
     * @return the List of converted objects.
     */
    <T> List<T> find(Query query, Class<T> entityClass);

    /**
     * Map the results of an ad-hoc query on the specified collection to a List of the specified type.
     * <br />
     * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless
     * configured otherwise, an instance of {@link MappingMongoConverter} will be used.
     * <br />
     * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
     * feature rich {@link Query}.
     *
     * @param query          the query class that specifies the criteria used to find a record and also an optional fields
     *                       specification. Must not be {@literal null}.
     * @param entityClass    the parametrized type of the returned list. Must not be {@literal null}.
     * @param collectionName name of the collection to retrieve the objects from. Must not be {@literal null}.
     * @return the List of converted objects.
     */
    <T> List<T> find(Query query, Class<T> entityClass, String collectionName);

    /**
     * Returns a document with the given id mapped onto the given class. The collection the query is ran against will be
     * derived from the given target class as well.
     *
     * @param id          the id of the document to return. Must not be {@literal null}.
     * @param entityClass the type the document shall be converted into. Must not be {@literal null}.
     * @return the document with the given id mapped onto the given target class.
     */
    @Nullable
    <T> T findById(Object id, Class<T> entityClass);

    /**
     * Returns the document with the given id from the given collection mapped onto the given target class.
     *
     * @param id             the id of the document to return.
     * @param entityClass    the type to convert the document to.
     * @param collectionName the collection to query for the document.
     * @return he converted object or {@literal null} if document does not exist.
     */
    @Nullable
    <T> T findById(Object id, Class<T> entityClass, String collectionName);

    /**
     * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
     * returns the results in a {@link List}.
     *
     * @param field       the name of the field to inspect for distinct values. Must not be {@literal null}.
     * @param entityClass the domain type used for determining the actual {@link MongoCollection}. Must not be
     *                    {@literal null}.
     * @param resultClass the result type. Must not be {@literal null}.
     * @return never {@literal null}.
     * @since 2.1
     */
    default <T> List<T> findDistinct(String field, Class<?> entityClass, Class<T> resultClass) {
        return findDistinct(new Query(), field, entityClass, resultClass);
    }

    /**
     * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
     * returns the results in a {@link List}.
     *
     * @param query       filter {@link Query} to restrict search. Must not be {@literal null}.
     * @param field       the name of the field to inspect for distinct values. Must not be {@literal null}.
     * @param entityClass the domain type used for determining the actual {@link MongoCollection} and mapping the
     *                    {@link Query} to the domain type fields. Must not be {@literal null}.
     * @param resultClass the result type. Must not be {@literal null}.
     * @return never {@literal null}.
     * @since 2.1
     */
    <T> List<T> findDistinct(Query query, String field, Class<?> entityClass, Class<T> resultClass);

    /**
     * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
     * returns the results in a {@link List}.
     *
     * @param query          filter {@link Query} to restrict search. Must not be {@literal null}.
     * @param field          the name of the field to inspect for distinct values. Must not be {@literal null}.
     * @param collectionName the explicit name of the actual {@link MongoCollection}. Must not be {@literal null}.
     * @param entityClass    the domain type used for mapping the {@link Query} to the domain type fields.
     * @param resultClass    the result type. Must not be {@literal null}.
     * @return never {@literal null}.
     * @since 2.1
     */
    <T> List<T> findDistinct(Query query, String field, String collectionName, Class<?> entityClass,
                             Class<T> resultClass);

    /**
     * Finds the distinct values for a specified {@literal field} across a single {@link MongoCollection} or view and
     * returns the results in a {@link List}.
     *
     * @param query       filter {@link Query} to restrict search. Must not be {@literal null}.
     * @param field       the name of the field to inspect for distinct values. Must not be {@literal null}.
     * @param collection  the explicit name of the actual {@link MongoCollection}. Must not be {@literal null}.
     * @param resultClass the result type. Must not be {@literal null}.
     * @return never {@literal null}.
     * @since 2.1
     */
    default <T> List<T> findDistinct(Query query, String field, String collection, Class<T> resultClass) {
        return findDistinct(query, field, collection, Object.class, resultClass);
    }

    /**
     * Returns the number of documents for the given {@link Query} by querying the collection of the given entity class.
     * <br />
     * <strong>NOTE:</strong> Query {@link Query#getSkip() offset} and {@link Query#getLimit() limit} can have direct
     * influence on the resulting number of documents found as those values are passed on to the server and potentially
     * limit the range and order within which the server performs the count operation. Use an {@literal unpaged} query to
     * count all matches.
     * <br />
     * This method uses an
     * {@link com.mongodb.client.MongoCollection#countDocuments(org.bson.conversions.Bson, com.mongodb.client.model.CountOptions)
     * aggregation execution} even for empty {@link Query queries} which may have an impact on performance, but guarantees
     * shard, session and transaction compliance. In case an inaccurate count satisfies the applications needs use
     * {@link MongoOperations#estimatedCount(Class)} for empty queries instead.
     *
     * @param query       the {@link Query} class that specifies the criteria used to find documents. Must not be
     *                    {@literal null}.
     * @param entityClass class that determines the collection to use. Must not be {@literal null}.
     * @return the count of matching documents.
     * @throws org.springframework.data.mapping.MappingException if the collection name cannot be
     *                                                           {@link org.springframework.data.mongodb.core.MongoOperations#getCollectionName(java.lang.Class)} from the given type.
     */
    long count(Query query, Class<?> entityClass);

    /**
     * Returns the number of documents for the given {@link Query} querying the given collection. The given {@link Query}
     * must solely consist of document field references as we lack type information to map potential property references
     * onto document fields. Use {@link MongoOperations#count(Query, Class, String)} to get full type specific support. <br />
     * <strong>NOTE:</strong> Query {@link Query#getSkip() offset} and {@link Query#getLimit() limit} can have direct
     * influence on the resulting number of documents found as those values are passed on to the server and potentially
     * limit the range and order within which the server performs the count operation. Use an {@literal unpaged} query to
     * count all matches.
     * <br />
     * This method uses an
     * {@link com.mongodb.client.MongoCollection#countDocuments(org.bson.conversions.Bson, com.mongodb.client.model.CountOptions)
     * aggregation execution} even for empty {@link Query queries} which may have an impact on performance, but guarantees
     * shard, session and transaction compliance. In case an inaccurate count satisfies the applications needs use
     * {@link MongoOperations#estimatedCount(String)} for empty queries instead.
     *
     * @param query          the {@link Query} class that specifies the criteria used to find documents.
     * @param collectionName must not be {@literal null} or empty.
     * @return the count of matching documents.
     * @see MongoOperations#count(Query, Class, String)
     */
    long count(Query query, String collectionName);

    /**
     * 更新插入
     * Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
     * combining the query document and the update document. <br />
     * <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
     * Use {@link MongoOperations#findAndModify(Query, UpdateDefinition, FindAndModifyOptions, Class, String)} instead.
     *
     * @param query       the query document that specifies the criteria used to select a record to be upserted. Must not be
     *                    {@literal null}.
     * @param update      the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                    the existing object. Must not be {@literal null}.
     * @param entityClass class that determines the collection to use. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given type.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass);

    /**
     * 更新插入
     * Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
     * combining the query document and the update document. <br />
     * <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
     * domain type information. Use {@link #upsert(Query, UpdateDefinition, Class, String)} to get full type specific
     * support. <br />
     * <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
     * Use {@link MongoOperations#findAndModify(Query, UpdateDefinition, FindAndModifyOptions, Class, String)} instead.
     *
     * @param query          the query document that specifies the criteria used to select a record to be upserted. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing object. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult upsert(Query query, UpdateDefinition update, String collectionName);

    /**
     * 更新插入
     * Performs an upsert. If no document is found that matches the query, a new document is created and inserted by
     * combining the query document and the update document.
     *
     * @param query          the query document that specifies the criteria used to select a record to be upserted. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing object. Must not be {@literal null}.
     * @param entityClass    class of the pojo to be operated on. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);

    /**
     * Updates the first object that is found in the collection of the entity class that matches the query document with
     * the provided update document.
     *
     * @param query       the query document that specifies the criteria used to select a record to be updated. Must not be
     *                    {@literal null}.
     * @param update      the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                    the existing. Must not be {@literal null}.
     * @param entityClass class that determines the collection to use.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given type.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass);

    /**
     * Updates the first object that is found in the specified collection that matches the query document criteria with
     * the provided updated document. <br />
     * <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
     * domain type information. Use {@link #updateFirst(Query, UpdateDefinition, Class, String)} to get full type specific
     * support. <br />
     * <strong>NOTE:</strong> {@link Query#getSortObject() sorting} is not supported by {@code db.collection.updateOne}.
     * Use {@link MongoOperations#findAndModify(Query, UpdateDefinition, Class, String)} instead.
     *
     * @param query          the query document that specifies the criteria used to select a record to be updated. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateFirst(Query query, UpdateDefinition update, String collectionName);

    /**
     * Updates the first object that is found in the specified collection that matches the query document criteria with
     * the provided updated document. <br />
     *
     * @param query          the query document that specifies the criteria used to select a record to be updated. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing. Must not be {@literal null}.
     * @param entityClass    class of the pojo to be operated on. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass, 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.
     *
     * @param query       the query document that specifies the criteria used to select a record to be updated. Must not be
     *                    {@literal null}.
     * @param update      the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                    the existing. Must not be {@literal null}.
     * @param entityClass class of the pojo to be operated on. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given type.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass);

    /**
     * Updates all objects that are found in the specified collection that matches the query document criteria with the
     * provided updated document. <br />
     * <strong>NOTE:</strong> Any additional support for field mapping, versions, etc. is not available due to the lack of
     * domain type information. Use {@link #updateMulti(Query, UpdateDefinition, Class, String)} to get full type specific
     * support.
     *
     * @param query          the query document that specifies the criteria used to select a record to be updated. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateMulti(Query query, UpdateDefinition 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.
     *
     * @param query          the query document that specifies the criteria used to select a record to be updated. Must not be
     *                       {@literal null}.
     * @param update         the {@link UpdateDefinition} that contains the updated object or {@code $} operators to manipulate
     *                       the existing. Must not be {@literal null}.
     * @param entityClass    class of the pojo to be operated on. Must not be {@literal null}.
     * @param collectionName name of the collection to update the object in. Must not be {@literal null}.
     * @return the {@link UpdateResult} which lets you access the results of the previous write.
     * @see Update
     * @see AggregationUpdate
     * @since 3.0
     */
    UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName);

    /**
     * Remove the given object from the collection by {@literal id} and (if applicable) its
     * {@link org.springframework.data.annotation.Version}. <br />
     * Use {@link DeleteResult#getDeletedCount()} for insight whether an {@link DeleteResult#wasAcknowledged()
     * acknowledged} remove operation was successful or not.
     *
     * @param object must not be {@literal null}.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given object type.
     */
    DeleteResult remove(Object object);

    /**
     * Removes the given object from the given collection by {@literal id} and (if applicable) its
     * {@link org.springframework.data.annotation.Version}. <br />
     * Use {@link DeleteResult#getDeletedCount()} for insight whether an {@link DeleteResult#wasAcknowledged()
     * acknowledged} remove operation was successful or not.
     *
     * @param object         must not be {@literal null}.
     * @param collectionName name of the collection where the objects will removed, must not be {@literal null} or empty.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     */
    DeleteResult remove(Object object, String collectionName);

    /**
     * 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.
     *
     * @param query       the query document that specifies the criteria used to remove a record.
     * @param entityClass class that determines the collection to use.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     * @throws IllegalArgumentException                          when {@literal query} or {@literal entityClass} is {@literal null}.
     * @throws org.springframework.data.mapping.MappingException if the target collection name cannot be
     *                                                           {@link MongoOperations#getCollectionName(Class) derived} from the given type.
     */
    DeleteResult remove(Query query, Class<?> entityClass);

    /**
     * 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.
     *
     * @param query          the query document that specifies the criteria used to remove a record.
     * @param entityClass    class of the pojo to be operated on. Can be {@literal null}.
     * @param collectionName name of the collection where the objects will removed, must not be {@literal null} or empty.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     * @throws IllegalArgumentException when {@literal query}, {@literal entityClass} or {@literal collectionName} is
     *                                  {@literal null}.
     */
    DeleteResult remove(Query query, Class<?> entityClass, String collectionName);

    /**
     * Remove all documents from the specified collection that match the provided query document criteria. There is no
     * conversion/mapping done for any criteria using the id field. <br />
     * <strong>NOTE:</strong> Any additional support for field mapping is not available due to the lack of domain type
     * information. Use {@link #remove(Query, Class, String)} to get full type specific support.
     *
     * @param query          the query document that specifies the criteria used to remove a record.
     * @param collectionName name of the collection where the objects will removed, must not be {@literal null} or empty.
     * @return the {@link DeleteResult} which lets you access the results of the previous delete.
     * @throws IllegalArgumentException when {@literal query} or {@literal collectionName} is {@literal null}.
     */
    DeleteResult remove(Query query, String collectionName);

}

实现类

java 复制代码
@Repository
public class MongoRepositoryImpl implements MongoRepository {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public MongoOperations getMongoTemplate() {
        return mongoTemplate;
    }

    @Override
    public MongoCollection<Document> getCollection(String collectionName) {
        return mongoTemplate.getCollection(collectionName);
    }

    @Override
    public MongoCollection<Document> getCollection(Query query, String collectionName) {
        mongoTemplate.count(query, collectionName);
        return mongoTemplate.getCollection(collectionName);
    }

    @Override
    public void insert(String collectionName, Document doc) {
        MongoCollection<Document> collection = getCollection(collectionName);
        collection.insertOne(doc);
    }

    @Override
    public long count(String collectionName, Bson filter) {
        MongoCollection<Document> collection = getCollection(collectionName);
        return collection.countDocuments(filter);
    }

    @Override
    public long countByLimit(String collectionName, Integer limit, Bson filter) {
        MongoCollection<Document> collection = getCollection(collectionName);
        CountOptions countOptions = new CountOptions();
        countOptions.limit(limit);
        return collection.countDocuments(filter, countOptions);
    }

    @Override
    public long distinctCount(String collectionName, Bson filter, String fieldName) {
        MongoCollection<Document> collection = getCollection(collectionName);
        long count = 0;
        if (StringUtils.isEmpty(fieldName)) {
            return 0L;
        }
        for (BsonValue ignored : collection.distinct(fieldName, filter, BsonValue.class)) {
            count++;
        }
        return count;
    }

    @Override
    public AggregateIterable<Document> aggregate(String collectionName, List<Bson> pipeline) {
        MongoCollection<Document> collection = getCollection(collectionName);
        return collection.aggregate(pipeline);
    }

    @Override
    public FindIterable<Document> find(String collectionName, Bson filter) {
        MongoCollection<Document> collection = getCollection(collectionName);
        return collection.find(filter);
    }

    @Override
    public long update(String collectionName, Bson filter, Document updateDoc) {
        MongoCollection<Document> collection = getCollection(collectionName);
        return collection.updateOne(filter, updateDoc).getModifiedCount();
    }

    @Override
    public String getCollectionName(Class<?> entityClass) {
        return mongoTemplate.getCollectionName(entityClass);
    }

    @Override
    public <T> T insert(T objectToSave) {
        return mongoTemplate.insert(objectToSave);
    }

    @Override
    public <T> T insert(T objectToSave, String collectionName) {
        return mongoTemplate.insert(objectToSave, collectionName);
    }

    @Override
    public <T> Collection<T> insert(Collection<? extends T> batchToSave, Class<?> entityClass) {
        return mongoTemplate.insert(batchToSave, entityClass);
    }

    @Override
    public <T> Collection<T> insert(Collection<? extends T> batchToSave, String collectionName) {
        return mongoTemplate.insert(batchToSave, collectionName);
    }

    @Override
    public <T> Collection<T> insertAll(Collection<? extends T> objectsToSave) {
        return mongoTemplate.insertAll(objectsToSave);
    }

    @Override
    public <T> T save(T objectToSave) {
        return mongoTemplate.save(objectToSave);
    }

    @Override
    public <T> T save(T objectToSave, String collectionName) {
        return mongoTemplate.save(objectToSave, collectionName);
    }

    @Override
    public <T> T findOne(Query query, Class<T> entityClass) {
        return mongoTemplate.findOne(query, entityClass);
    }

    @Override
    public <T> T findOne(Query query, Class<T> entityClass, String collectionName) {
        return mongoTemplate.findOne(query, entityClass, collectionName);
    }

    @Override
    public boolean exists(Query query, String collectionName) {
        return mongoTemplate.exists(query, collectionName);
    }

    @Override
    public boolean exists(Query query, Class<?> entityClass) {
        return mongoTemplate.exists(query, entityClass);
    }

    @Override
    public boolean exists(Query query, Class<?> entityClass, String collectionName) {
        return mongoTemplate.exists(query, entityClass);
    }

    @Override
    public <T> List<T> find(Query query, Class<T> entityClass) {
        return mongoTemplate.find(query, entityClass);
    }

    @Override
    public <T> List<T> find(Query query, Class<T> entityClass, String collectionName) {
        return mongoTemplate.find(query, entityClass, collectionName);
    }

    @Override
    public <T> T findById(Object id, Class<T> entityClass) {
        return mongoTemplate.findById(id, entityClass);
    }

    @Override
    public <T> T findById(Object id, Class<T> entityClass, String collectionName) {
        return mongoTemplate.findById(id, entityClass, collectionName);
    }

    @Override
    public <T> List<T> findDistinct(String field, Class<?> entityClass, Class<T> resultClass) {
        return mongoTemplate.findDistinct(field, entityClass, resultClass);
    }

    @Override
    public <T> List<T> findDistinct(Query query, String field, Class<?> entityClass, Class<T> resultClass) {
        return mongoTemplate.findDistinct(query, field, entityClass, resultClass);
    }

    @Override
    public <T> List<T> findDistinct(Query query, String field, String collectionName, Class<?> entityClass, Class<T> resultClass) {
        return mongoTemplate.findDistinct(query, field, collectionName, entityClass, resultClass);
    }

    @Override
    public <T> List<T> findDistinct(Query query, String field, String collection, Class<T> resultClass) {
        return mongoTemplate.findDistinct(query, field, collection, resultClass);
    }

    @Override
    public long count(Query query, Class<?> entityClass) {
        return mongoTemplate.count(query, entityClass);
    }

    @Override
    public long count(Query query, String collectionName) {
        return mongoTemplate.count(query, collectionName);
    }

    @Override
    public UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass) {
        return mongoTemplate.upsert(query, update, entityClass);
    }

    @Override
    public UpdateResult upsert(Query query, UpdateDefinition update, String collectionName) {
        return mongoTemplate.upsert(query, update, collectionName);
    }

    @Override
    public UpdateResult upsert(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
        return mongoTemplate.upsert(query, update, entityClass, collectionName);
    }

    @Override
    public UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass) {
        return mongoTemplate.updateFirst(query, update, entityClass);
    }

    @Override
    public UpdateResult updateFirst(Query query, UpdateDefinition update, String collectionName) {
        return mongoTemplate.updateFirst(query, update, collectionName);
    }

    @Override
    public UpdateResult updateFirst(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
        return mongoTemplate.updateFirst(query, update, entityClass, collectionName);
    }

    @Override
    public UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass) {
        return mongoTemplate.updateMulti(query, update, entityClass);
    }

    @Override
    public UpdateResult updateMulti(Query query, UpdateDefinition update, String collectionName) {
        return mongoTemplate.updateMulti(query, update, collectionName);
    }

    @Override
    public UpdateResult updateMulti(Query query, UpdateDefinition update, Class<?> entityClass, String collectionName) {
        return mongoTemplate.updateMulti(query, update, entityClass, collectionName);
    }

    @Override
    public DeleteResult remove(Object object) {
        return mongoTemplate.remove(object);
    }

    @Override
    public DeleteResult remove(Object object, String collectionName) {
        return mongoTemplate.remove(object, collectionName);
    }

    @Override
    public DeleteResult remove(Query query, Class<?> entityClass) {
        return mongoTemplate.remove(query, entityClass);
    }

    @Override
    public DeleteResult remove(Query query, Class<?> entityClass, String collectionName) {
        return mongoTemplate.remove(query, entityClass, collectionName);
    }

    @Override
    public DeleteResult remove(Query query, String collectionName) {
        return mongoTemplate.remove(query, collectionName);
    }
}

后续直接使用仓库类即可

测试类

java 复制代码
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class ProcessTest {

    @Autowired
    private MongoRepository mongoRepository;

    @Test
    public void test() {
        String collectionName = mongoGateway.getCollectionName(User.class);
        System.out.println(collectionName);
        User user = new User();
        user.setId(1L);
        user.setUser_id(1111L);
        user.setAge(10);
        User user1 = mongoRepository.save(user, "user");
        System.out.println("新增user: " + JSON.toJSONString(user1));

        Query query = new Query();
        Criteria criteria = new Criteria(TableInfoEnum.USER.getUniqueFieldName());
        criteria.is(user.getUser_id());
        query.addCriteria(criteria);

        user.setAge(18);
        Update update = new Update();
        setUpdate(update, user);
        mongoRepository.updateMulti(query, update, User.class, "user");

        User one = mongoRepository.findOne(query, User.class, "user");
        System.out.println("one: " + JSON.toJSONString(one));
    }

    public void setUpdate(Update update, Object object) {
        if (null == object) {
            return;
        }
        Class<?> clazz = object.getClass();

        BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(clazz);

            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                String name = propertyDescriptor.getName();
                if (!"class".equalsIgnoreCase(name)) {
                    Method readMethod = propertyDescriptor.getReadMethod();
                    readMethod.setAccessible(true);
                    Object invoke = readMethod.invoke(object, null);
                    if (null != invoke) {
                        update.set(name, invoke);
                        System.out.println("name: " + name + " invoke: " + invoke);
                    }
                }

            }
        } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
            log.error("setUpdate属性失败,错误日志: {[]}", e);
        }
    }
}

官方文档参考: https://docs.spring.io/spring-data/mongodb/reference/mongodb.html

the end !!!

相关推荐
用户608186527902 分钟前
WPF 命令 ICommand 从原理到实战
后端
liuqun03195 分钟前
go进阶之gc
开发语言·后端·golang
李小狼lee5 分钟前
以一个简单案例来讲解RAG
后端
程序员清风9 分钟前
OpenAI创始人学AI的底层逻辑,普通人照着做就能上手!
java·后端·面试
元俭10 分钟前
【Eino 框架入门】用 JSONL 实现会话持久化
后端
Memory_荒年12 分钟前
Netty面试终极指南:从“Hello World”到源码深处
java·后端
0xDevNull12 分钟前
Java IO流教程:从入门到最佳实践
java·后端
Memory_荒年17 分钟前
Netty深度解构:高性能背后的核心机制与实战精要
java·后端
平平无奇的开发仔19 分钟前
通过@Transational注解的对象,简单了解SpringAop是如何执行的
后端
Lyyaoo.20 分钟前
Spring,Spring MVC, Spring Boot
spring boot·spring·mvc