• SpringBoot2.1.9 MongoDB逻辑操作


    一、基础类配置

    1. @NoRepositoryBean
    2. public interface IMongoRepository extends MongoRepository {
    3. String getTableName();
    4. void deleteAll(Collection ids);
    5. MongoOperations getMongoOperations();
    6. MongoEntityInformation getEntityInformation();
    7. Class getEntityClass();
    8. Class getIdClass();
    9. }
    1. public class AbstractMongoRepository extends SimpleMongoRepository implements IMongoRepository {
    2. private final MongoOperations mongoOperations;
    3. private final MongoEntityInformation entityInformation;
    4. public AbstractMongoRepository(MongoEntityInformation metadata, MongoOperations mongoOperations) {
    5. super(metadata, mongoOperations);
    6. this.mongoOperations = mongoOperations;
    7. this.entityInformation = metadata;
    8. }
    9. @Override
    10. public String getTableName(){
    11. return entityInformation.getCollectionName();
    12. }
    13. @Override
    14. public void deleteAll(Collection ids) {
    15. ids.forEach(this::deleteById);
    16. }
    17. @Override
    18. public MongoOperations getMongoOperations() {
    19. return mongoOperations;
    20. }
    21. @Override
    22. public MongoEntityInformation getEntityInformation() {
    23. return entityInformation;
    24. }
    25. @Override
    26. public Class getEntityClass() {
    27. return entityInformation.getJavaType();
    28. }
    29. @Override
    30. public Class getIdClass() {
    31. return entityInformation.getIdType();
    32. }
    33. }
    1. @SpringBootApplication
    2. @EnableMongoRepositories(repositoryBaseClass = AbstractMongoRepository.class)
    3. public class MongoApplication {
    4. public static void main(String[] args) {
    5. SpringApplication.run(MongoApplication.class, args);
    6. }
    7. }

    而、查询

    (1)普通查询

    1. public interface UserRepository extends IMongoRepository {
    2. //jpa根据名字自动适配查询
    3. List findByName(String name);
    4. List findByNameAndAge(String name, int age);
    5. //手动指定查询
    6. default List listByNameAndAge(String name, int age){
    7. Query q = new Query(Criteria.where(User.Fields.name).is(name)
    8. .and(User.Fields.age).is(age));
    9. return this.getMongoOperations().find(q, this.getEntityClass());
    10. }
    11. default List find(ObjectId id){
    12. Query q = new Query(Criteria.where("_id").is(id));
    13. return this.getMongoOperations().find(q, this.getEntityClass());
    14. }
    15. default Optional find2(ObjectId id){
    16. return this.findById(id);
    17. }
    18. default List listByAge(int ageMin,int ageMax) {
    19. Query q = new Query(Criteria.where(User.Fields.name).exists(true)
    20. .andOperator(Criteria.where(User.Fields.age).gte(ageMin),
    21. Criteria.where(User.Fields.age).lt(ageMax)));
    22. return this.getMongoOperations().find(q, User.class, this.getTableName());
    23. }
    24. }

    (2)排序

    1. public interface UserRepository extends IMongoRepository {
    2. default List listSort(int age){
    3. Query q = new Query(Criteria.where(User.Fields.age).is(age));
    4. q.with(Sort.by(Sort.Order.desc(User.Fields.name), Sort.Order.desc(User.Fields.age)));
    5. return this.getMongoOperations().find(q, this.getEntityClass());
    6. }
    7. }

    (3)分页

    1. public interface UserRepository extends IMongoRepository {
    2. default List listLimit(int age){
    3. Query q = new Query(Criteria.where(User.Fields.age).is(age));
    4. q.skip(50).limit(10);
    5. return this.getMongoOperations().find(q, this.getEntityClass());
    6. }
    7. }

    二、更新

    1. public interface UserRepository extends IMongoRepository {
    2. default void update(User user){
    3. this.save(user);
    4. }
    5. default long updateAge(ObjectId id, int age){
    6. Query q = new Query(Criteria.where("_id").is(id));
    7. Update update = new Update();
    8. update.set(User.Fields.age, age);
    9. return this.getMongoOperations().updateFirst(q, update, getTableName()).getModifiedCount();
    10. }
    11. default long updateAge(String name, int age){
    12. Query q = new Query(Criteria.where(User.Fields.name).is(name));
    13. Update update = new Update();
    14. update.set(User.Fields.age, age);
    15. return this.getMongoOperations().updateMulti(q, update, getTableName()).getModifiedCount();
    16. }
    17. }

    三、删除

    1. public interface UserRepository extends IMongoRepository {
    2. default void delete(ObjectId id){
    3. this.deleteById(id);
    4. }
    5. default void delete1(User user){
    6. this.delete(user);
    7. }
    8. default DeleteResult delete2(ObjectId id){
    9. Query q = new Query(Criteria.where("_id").is(id));
    10. return this.getMongoOperations().remove(q, getTableName());
    11. }
    12. }

    四、索引

    1. public interface UserRepository extends IMongoRepository {
    2. default void createIndex() {
    3. MongoCollection collection = getMongoOperations().getCollection(getTableName());
    4. BasicDBObject indexOptions = new BasicDBObject();
    5. indexOptions.put(User.Fields.name, -1);
    6. String alarmSummaryId = collection.createIndex(indexOptions);
    7. indexOptions = new BasicDBObject();
    8. indexOptions.put(User.Fields.age, 1);
    9. String createAt = collection.createIndex(indexOptions);
    10. }
    11. }

    五、聚合

    1. public interface UserRepository extends IMongoRepository {
    2. default Map listAgeFirstCity(int skip, int limit){
    3. Criteria criteria = Criteria.where(User.Fields.city).exists(true);
    4. Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
    5. Aggregation.group(User.Fields.age).first( "$city").as( "city"),
    6. Aggregation.skip(skip), Aggregation.limit(limit));
    7. List list = this.getMongoOperations().aggregate(aggregation, getTableName(), Map.class).getMappedResults();
    8. Map data = new HashMap<>();
    9. for(Map map : list){
    10. data.put((ObjectId) map.get("_id"), (String)map.get("city"));
    11. }
    12. return data;
    13. }
    14. }

    六、连接

    1. public interface UserRepository extends IMongoRepository {
    2. default List list() {
    3. LookupOperation lookupOperation= LookupOperation.newLookup().
    4. from(AdminRepository.instance().getTableName()). //关联从表名
    5. localField(User.Fields.name). //主表关联字段
    6. foreignField(Admin.Fields.name).//从表关联的字段
    7. as("adminInfo"); //查询结果名
    8. Criteria left = Criteria.where(User.Fields.city).exists(true)
    9. .andOperator(Criteria.where(User.Fields.age).gte(18),
    10. Criteria.where(User.Fields.age).lt(65));
    11. Criteria right = Criteria.where("adminInfo.0").exists(true).and("adminInfo.0.admin").is(1);
    12. Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(left), lookupOperation,
    13. Aggregation.match(right), Aggregation.unwind("adminInfo", true));
    14. List results = this.getMongoOperations().aggregate(aggregation, this.getTableName(), UserVo.class).getMappedResults();
    15. return results;
    16. }
    17. @Setter
    18. @Getter
    19. public static class UserVo extends User{
    20. private Admin adminInfo;
    21. }
    22. }

  • 相关阅读:
    Spring Cloud Netflix 知识整理
    EasyRecovery2023重新找回丢失的文件数据恢复软件
    代码随想录二刷day59
    pyyaml操作yaml配置文件基于python
    java面试题
    react中的this指向问题
    Nlog详解---非常详细
    字节架构师分析Spring Boot源码:日志、缓存、Web服务等
    【MySQL】视图、函数、存储过程优缺点
    电脑C盘爆红怎么办?(小白篇)
  • 原文地址:https://blog.csdn.net/moakun/article/details/127135909