Main Contents of this paper

  • Examples of basic MongoDB operation commands
  • MongoDB uploads, downloads, deletes files with GridFSTemplate (Work Focus)

1. Basic commands

Create database name: horse, create collection name: blog

DropDatebase () # dropDatebase() # dropDatebase() # dropDatebase() #"horse",pwd:"mongo123",roles:[{role:"readWrite",db:"horse"}]}) # create db.createcollection ("blog"Db.blog. Drop () # show collections # insert db.blog. Drop () # insert db.blog."name":"Tom"."age":23."sex":true})
db.blog.insertOne({"name":"Top"."age":20."sex":true})
db.blog.insertMany([{"name":"Jerry"."age":22."sex":false}, {"name":"Free"."age":21."sex":true}]) # update db.blog.update({"name":"Top"},{$set:{"name":"TopSun"}},{multi:true}) # delete db.blog.remove({"sex":false}, true)
db.blog.deleteMany({"age":23})
db.blog.deleteOne({"age":22}) # delete db.blog.deleteman ({}) # delete db.blog.find(). Pretty () # delete db.blog.find()."name":"Tom"}) # query db.blog.find({db.blog."age":{$lt: 23},"name":"Free"}). Pretty () # default and connect db.blog.find({$or:[{$or:[{$or:[{$or:[})."age":{$lt:23}}, {"name":"Free"}]}). Pretty () # or db.blog.find({"age":{$lt:23},$or:[{"name":"Free"}, {"sex":"false"}]}).pretty() # and db.blog.find().limit()2).skip(1).sort({"age":1}). Pretty () # limit, skip, sort used in combination (execution sequence: sort - > skip - > limit) # aggregation query (reference) db. Blog. Aggregate ([{$group: {_id:"$age",count:{$sum:1}}}])

Copy the code

2. GridFsTemplate use

2.1 Introducing POM dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
Copy the code

2.2 configuration yml


spring:
  data:
    mongodb:
      host: *. *. *. *
      username: * * *
      password: * * *
      database: * * *
      port: 27017
 # set file upload size limit
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 50MB
Copy the code

2.3 Upload, Download and Delete

Face the Wind: Engaging HuTool kit for better eating!!

/ * * *@author Mr.Horse
 * @version 1.0
 * @description: MongoDB file upload, download, delete and other basic operations (collection of HuTool tool library) *@date 2021/4/29 9:53
 */
@Validated
@Controller
@RequestMapping("/mongo")
public class MongoUploadController {

    private static Logger logger = LoggerFactory.getLogger(MongoUploadController.class);

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/gif"."image/jpeg"."image/jpg"."image/png");

    /** * MongoDB file upload **@param file
     * @return* /
    @PostMapping("/upload")
    public ResponseEntity<String> fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            // Verify file information (file type, file content)
            String originalFilename = file.getOriginalFilename();
            if (StrUtil.isBlank(originalFilename)) {
                return ResponseEntity.badRequest().body("Parameter error");
            }
            String contentType = file.getContentType();
            if(! CONTENT_TYPES.contains(contentType)) {return ResponseEntity.badRequest().body("File type error");
            }
            InputStream inputStream = file.getInputStream();
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            if (ObjectUtil.isEmpty(bufferedImage)) {
                return ResponseEntity.badRequest().body("File contents error");
            }

            // Rename the file
            String suffix = FileNameUtil.getSuffix(originalFilename);
            String fileName = IdUtil.simpleUUID().concat(".").concat(suffix);

            // File upload, return to ObjectId
            ObjectId objectId = gridFsTemplate.store(inputStream, fileName, contentType);
            return StrUtil.isBlank(String.valueOf(objectId)) ? ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed") : ResponseEntity.ok(String.valueOf(objectId));
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("File upload exception"); }}/** * The ObjectId file will be read and the response stream will be written to the page. You can download and display the file **@param objectId
     */
    @GetMapping("/read")
    public void queryFileByObjectId(@RequestParam("objectId") @notblank (message = "ObjectId cannot be empty ") String objectId, HttpServletResponse response) {
        Query files based on objectId
        GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(objectId)));
        // Create a file bucket
        GridFSBucket gridFsBucket = GridFSBuckets.create(mongoTemplate.getDb());
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            if (ObjectUtil.isNotNull(file)) {
                // Open the download stream object
                GridFSDownloadStream fileStream = gridFsBucket.openDownloadStream(file.getObjectId());
                // Create girdFsResource, pass in the download stream object, get the stream object
                GridFsResource gridFsResource = new GridFsResource(file, fileStream);
                // Write to the output stream
                inputStream = gridFsResource.getInputStream();
                outputStream = response.getOutputStream();
                byte[] bytes = new byte[1024];
                if(inputStream.read(bytes) ! = -1) { outputStream.write(bytes); }}}catch (IOException e) {
            logger.error("File reading exception: {}", e.getMessage());
        } finally{ IoUtil.close(outputStream); IoUtil.close(inputStream); }}/** * Delete files based on ObjectId **@param objectId
     * @return* /
    @DeleteMapping("/remove")
    public ResponseEntity<String> removeFileByObjectId(@RequestParam("objectId") @notblank (message = "ObjectId cannot be empty ") String objectId) {
        gridFsTemplate.delete(new Query(Criteria.where("_id").is(objectId)));
        return ResponseEntity.ok("Deleted successfully"); }}Copy the code

If you want to download the resource on the browser page, you can combine it with JS (the file type depends on service requirements). The main implementation code is as follows:

    downloadNotes(noteId) {
      axios({
        url: this.BASE_API + '/admin/mongo/file/query/' + noteId,
        method: 'get'.responseType: 'arraybuffer'.params: { type: 'download' }
      }).then(res= > {
        // Type can be set to text, in this case PDF
        const pdfUrl = window.URL.createObjectURL(new Blob([res.data], { type: `application/pdf` }))
        const fname = noteId // Download the file name
        const link = document.createElement('a')
        link.href = pdfUrl
        link.setAttribute('download', fname)
        document.body.appendChild(link)
        link.click()
        URL.revokeObjectURL(pdfUrl) // Release the URL object})}Copy the code