当前位置:网站首页>Mongodb uses mongotemplate operations to add, delete, modify, query, page, sort, aggregate (including embedded data), file upload and download

Mongodb uses mongotemplate operations to add, delete, modify, query, page, sort, aggregate (including embedded data), file upload and download

2022-07-24 13:20:00 A bird jumping off a cliff to die

MongoDB Brief introduction

MongoDB It's open source 、 High performance 、 A modeless document database , It was designed to simplify development and facilitate expansion , yes NoSQL One of the database products . It is most like a relational database (MySQL) Non relational database .
The data structure it supports is very loose , It's something like JSON Of Format call BSON, So it can store complex data types , And quite flexible .

Dependency package

       <!--springboot yes 2.1.6.RELEASE-->

         <!-- operation MongoDB Core packages -->
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <!-- Simplify the operation of entity classes and logs -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>

yml Simple configuration

spring:
  data:
    mongodb:
      host: 192.168.142.139
      database: articledb# Database name 
      port: 27017
      # You can also use uri Connect 
     #uri: mongodb://192.168.142.139:27017/articledb

Entity class

@Data// amount to get/set Method 
@Document(collection="comment")// The set name of the corresponding database ( Table name )
// Composite index 
//@CompoundIndex( def = "{'userid': 1, 'nickname': -1}")
public class Comment implements Serializable {
    
    // Primary key identification , The value of this property automatically corresponds to mongodb Primary key field of "_id", If the property name is called “id”, The note may be omitted , Otherwise you have to write 
    @Id
    private String id;// Primary key 
    // This attribute corresponds to mongodb The name of the field of , If the same , There is no need for the annotation 
    @Field("content")
    private String content;// Make complaints about content 
    private Date publishtime;// Release date 
    // An index with a single field is usually added in the database 
    @Indexed
    private String userid;// Issued by ID
    private String nickname;// nickname 
    private LocalDateTime createdatetime;// Date and time of comment 
    private Integer likenum;// Number of likes 
    private Integer replynum;// Number of replies 
    private String state;// state 
    private String parentid;// The superior ID
    private String articleid;
    private List<User> users;// Create an entity class by yourself User Test embedded data 
}

Non embedded form

increase (insert)

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Comment insert(Comment comment) {
    
        log.info(" Simple new start ");
        Comment insert = mongoTemplate.insert(comment);
        return insert;
    }

Add multiple records
mongoTemplate.insert( Data combination ,Comment.class);

Delete (remove)

According to the entity class object deletion test, only settings id Can only be

   @Override
    public Long removeObj() {
    
        log.info("removeObj()");
        Comment comment = new Comment();
        comment.setId("1");
        DeleteResult remove = mongoTemplate.remove(comment);
        long deletedCount = remove.getDeletedCount();
        return deletedCount;
    }

Delete... According to conditions (Query object ) This is recommended

    @Override
    public Long removeQuery() {
    
        log.info("removeQuery");
        Query query = new Query();
        // hold userid==100 The deletion of 
        Criteria criteria = Criteria.where("userid").is("100");
        query.addCriteria(criteria);
        DeleteResult remove = mongoTemplate.remove(query, Comment.class);
        return remove.getDeletedCount();
    }

Change (updateFirst|updateMulti)

mongoTemplate.updateFirst(query, update, Comment.class); Update the first matching data

 @Override
    public Long updateFirstComment() {
    
        log.info("updateFirstComment");
        Query query = Query.query(Criteria.where("userid").is("1003"));
        Update update = new Update();
        update.set("nickname", "updateFirstComment");
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Comment.class);
        System.out.println(updateResult.getMatchedCount());
        return updateResult.getMatchedCount();
    }

UpdateResult updateMulti(Query query, Update update, Class<?> entityClass); Update all data matching the criteria

 @Override
    public Long updateMultiComment() {
    
        log.info("updateMultiComment");
        Query query = Query.query(Criteria.where("userid").is("1003"));
        Update update = new Update();
        update.set("nickname", "updateMultiComment");
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Comment.class);
        System.out.println(updateResult.getMatchedCount());
        return updateResult.getMatchedCount();
    }

UpdateResult upsert(Query var1, Update var2, Class<?> var3); If the data does not exist, add one

check

Check all the results (findAll)

 @Override
    public List<Comment> findAll() {
    
        //Comment.class Entity class class object 
        log.info("findAll");
        List<Comment> all = mongoTemplate.findAll(Comment.class);
        return all;
    }

Conditions of the query – or (or)

    @Override
    public List<Comment> findQueryComment() {
    
        // Conditions for a 
        Criteria criteria1 = new Criteria();
        criteria1.and("users.id").is("001");
        // Condition 2 
        Criteria criteria2 = new Criteria();
        criteria2.and("userid").is("1003");
        // Set up the conditions 
        Criteria criteria = new Criteria();
        criteria.orOperator(criteria1,criteria2);
        Query query = new Query();
        query.addCriteria(criteria);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

Conditions of the query – And (and)

    @Override
    public List<Comment> findQueryComment() {
    

        Criteria criteria = new Criteria();
        // And simpler than or 
        criteria.and("users.id").is("1").and("userid").is("100");
        Query query = new Query();
        query.addCriteria(criteria);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

Conditions of the query - Fuzzy query (regex)

    @Override
    public List<Comment> findQueryComment() {
    

        Query query = new Query();
        Criteria criteria = new Criteria();
        // Regular 
        criteria.and("userid").regex("^.*"+0+".*$");
        query.addCriteria(criteria);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        
        return comments;
    }

Conditions of the query - Total number of checks (count )

@Override
    public Long findQueryComment() {
    

        Query query = new Query();
        Criteria criteria = new Criteria();
        // Regular 
        criteria.and("userid").regex("^.*"+0+".*$");
        query.addCriteria(criteria);
        long count = mongoTemplate.count(query, Comment.class);

        return count;
    }

Conditions of the query - Sort (sort)

   @Override
    public List<Comment> findQueryComment() {
    
       // Conditions 
        Query query = Query.query(Criteria.where("userid").is("1003"));
        // Sort rule   hold id In reverse order 
        Sort sort = new Sort(Sort.Direction.DESC,"_id");
        query.with(sort);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

Conditions of the query - Pagination (Pageable)

 @Override
    public List<Comment> findQueryComment() {
    
       // Conditional body 
        Query query = new Query();
        // Sort rule   hold id In reverse order 
        Sort sort = new Sort(Sort.Direction.DESC,"_id");
        // The current page + The size of the page ( The current page should be the actual number of pages minus one )
        PageRequest page = PageRequest.of(0, 2);
        query.with(sort);
        // Pagination  === It can also be used. query.skip( The current page -1).limit( The size of the page )
        query.with(page);
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

Aggregate query (Aggregation )

        Criteria criteria = new Criteria();
    
        criteria.and("users.id").is("1").and("userid").is("100");
        //Aggregation.group("userid").count().as("total")
        //count  Aggregate functions ( and SQL equally )
        Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(criteria),
                Aggregation.group("userid").count().as("total"),
                Aggregation.sort(Sort.Direction.DESC, "total"));
    //comment Table name  JSONObject.class The type of return , You can self encapsulate the entity class attribute name, which can be injected only if it is the same as the alias of the aggregation , similar mybatis
        AggregationResults<JSONObject> aggregate = mongoTemplate.aggregate(aggregation,
                "comment", JSONObject.class);
     List<JSONObject> Comments =  aggregate.getMappedResults();

Embedded add data

If you want to users How to add a piece of data to the set of ?

{
    
    "_id":"5eec4eaeefe450068c1dc854",
    "content":" I am simply adding ",
    "userid":"100",
    "createdatetime":"2020-06-19T05:35:42.389Z",
    "likenum":10,
    "parentid":"1003",
    "articleid":"100",
    "users":[
        {
    
            "_id":"1",
            "name":" Xiao Ming "
        }
    ],
    "_class":"com.hlxy.mongodb.pojo.Comment"
}

increase (update.push( Field , value );)

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Long pushUser() {
    
        Query q = Query.query(Criteria.where("_id").is("1"));
        User user = new User();
        user.setId("003");
        user.setName(" millet ");
        Update update = new Update();
        //users Field name   hold user Add to users Data embedded in the set of 
        update.push("users",user);
        UpdateResult updateResult = mongoTemplate.updateFirst(q, update, Comment.class);
        return updateResult.getMatchedCount();
    }

Delete (update.pull(“ Field ”, object );)

    @Override
    public Long pullUser() {
    
        Query q = Query.query(Criteria.where("_id").is("1"));
        User user = new User();
        user.setId("003");
        Update update = new Update();
        //users Field name  users Find a match in user Delete 
        update.pull("users",user);
        UpdateResult updateResult = mongoTemplate.updateFirst(q, update, Comment.class);
        return updateResult.getMatchedCount();
    }

update.pullAll(“ Field ”, aggregate )

Change (update.set)

update.set(“users.$.name”,“ value ”);// modify users.name As an example
Generally add "users.name" As a screening condition

 @Override
    public Long updateComment() {
    
      
        Query query =  Query.query(Criteria.where("_id").is("5eec3048efe4502f201b7ea8"));
        // Modify the conditions - Clear to modify users Which data in the array ,, If you don't write it, it's in the whole users Match... In the array 
        query.addCriteria(Criteria.where("users.name").is(" Xiao Ming ")))
        Update update = new Update();
        update.set("users.$.name"," The data has changed ");
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Comment.class);
        return updateResult.getMatchedCount();
    }

If you are modifying multiple pieces of data $ Change to $ []
update.set(“users.$[].name”,“ All the data have been changed ”);

check (find)

Query basically unchanged field name :users.id

  @Override
    public List<Comment> find() {
    
        Query query = Query.query(Criteria.where("users.id").is("003"));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

The query returns the specified field

query.fields().include(“ Field ”); // Include this field
query.fields().exclude(“ Field ”);// Do not include this field

    @Override
    public List<Comment> find() {
    
        Query query = Query.query(Criteria.where("users.id").is("003"));
        query.fields().exclude("users");
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

Upload files

// @Autowired
// private GridFsTemplate gridFsTemplate;--- and mongoTemplate Just inject the same 
 ObjectId store = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), file.getContentType());
String fileId = store.toHexString();// file id- Download to use - Keep it 

File download

  String id = fileId;//fileId It is the file returned when uploading id
  // According to the document id Get download information 
 GridFSFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
        if(file!=null){
    
             // get files 
            GridFsResource gridFsResource = new GridFsResource(file, GridFSBuckets.create(mongoTemplate.getDb()).openDownloadStream(file.getObjectId()));
          // File name 
            String fileName = URLEncoder.encode(gridFsResource.getFilename(), "UTF-8");
            // Set download properties 
            response.setContentType(gridFsResource.getContentType());
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            // Input the obtained file stream to  response The output stream of ( download )
            IOUtils.copy(gridFsResource.getInputStream(),outputStream);
        }
原网站

版权声明
本文为[A bird jumping off a cliff to die]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/203/202207211747298060.html