java(基于springboot项目或maven项目均可) 操作mongodb

一、引入mongodb 坐标依赖
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
二、创建mongodb 配置文件 mongodb.properties
添加如下内容
mymongodb.host= 10.0.0.2
mymongodb.port= 27017
mymongodb.dbname= articledb

   三、创建mongodb 工具类

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @Description: [mongodb工具类]
 * @Author: Jingqi Qu
 * @CreateDate: 2021/12/21 17:17
 * @UpdateUser:
 * @UpdateDate:
 * @Version: [v1.0]
 */
@Configuration
@ConfigurationProperties(prefix = "mymongodb", ignoreUnknownFields = false)
@PropertySource("classpath:config/mongodb.properties")
@Data
@Component
public class MongoDBUtil {



    private  String host;
    private  int port;
    private  String dbname;
    private static MongoDatabase mongoDatabase;


    public  MongoClient getMongoClient(){//创建方法不同版本依赖可能不同,查看源码即可 此处使用 host +默认端口号创建
     //创建client
MongoClient mongoClient = new MongoClient(host); return mongoClient; } public MongoDatabase getMongoDatabase(){ MongoClient mongoClient = getMongoClient();
mongoDatabase
= mongoClient.getDatabase(dbname); return mongoDatabase; } // 使用Grid 链接指定数据库 public GridFSBucket getGrid(){ MongoClient mongoClient = getMongoClient(); MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname); GridFSBucket gridFSBucket = GridFSBuckets.create(mongoDatabase); return gridFSBucket; } }

四、使用mongodbapi操作mongodb数据库

 

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSUploadStream;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.junit.Test;

import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description: [一句话描述该类的功能]
 * @Author: Jingqi Qu
 * @CreateDate: 2021/12/21 17:43
 * @UpdateUser:
 * @UpdateDate:
 * @Version: [v1.0]
 */

public class TestMongo {


    // 查看mongodb所有数据库
    @Test
    public void getAllDB(){
        MongoClient  mongoClient = MongoDBUtil.getMongoClient();
        MongoIterable<String> mongoIterable = mongoClient.listDatabaseNames();
        for(String db:mongoIterable){
            System.out.println(db);
        }
    }

    // 查看指定数据库下的所有集合
    @Test
    public void getCollections(){
        MongoDatabase db = MongoDBUtil.getMongoDatabase();
        MongoIterable<String> nameList = db.listCollectionNames();
        for(String collectionsName :nameList){
            System.out.println(collectionsName);
        }
    }

    // 创建集合
    @Test
    public void createCollections(){
        MongoDatabase db = MongoDBUtil.getMongoDatabase();
        db.createCollection("threeCollection");

    }
    // 删除集合
    @Test
    public void removeCollections(){
        MongoDatabase db = MongoDBUtil.getMongoDatabase();
        MongoCollection<Document> collection =  db.getCollection("threeCollection");
        collection.drop();

    }

    // 根据集合名获取所有文档
    @Test
    public void findDocumentByCollectionName(){
        MongoDatabase db = MongoDBUtil.getMongoDatabase();
        MongoCollection<Document> collection =  db.getCollection("threeCollection");
        FindIterable<Document> doc =  collection.find();
        for(Document document :doc){
            System.out.println(document);
        }

    }
    // 插入文档
    @Test
    public void insertDocumentByCollectionName(){
        MongoDatabase db = MongoDBUtil.getMongoDatabase();
        MongoCollection<Document> collection =  db.getCollection("threeCollection");
        Document doc = new Document();
        Map<String,String> map = new HashMap<String, String>();
        map.put("class","222");
        //默认是个ObjectId对象,此处设置为string,否则无法更新
        doc.append("_id","44444");
        doc.append("name","tom3");
        doc.append("age","68");
        collection.insertOne(doc);

    }
    // 更新文档
    @Test
    public void updateDocumentByCollectionName(){
        MongoDatabase db = MongoDBUtil.getMongoDatabase();
        MongoCollection<Document> collection =  db.getCollection("threeCollection");
        Document doc = new Document("class","888");
        UpdateResult a = collection.updateOne(Filters.eq("class","222"),new Document("$set",doc));
        System.out.println(a);

    }

    // 删除文档
    @Test
    public void removeDocumentByCollectionName(){
        MongoDatabase db = MongoDBUtil.getMongoDatabase();
        MongoCollection<Document> collection =  db.getCollection("threeCollection");
        DeleteResult res = collection.deleteOne(Filters.eq("_id","61c2c911136fb13d507f5b4f"));
        System.out.println(res);

    }


    // MongoDB GridFS  存图片
    @Test
    public void test(){
        GridFSBucket grid = MongoDBUtil.getGrid();
        GridFSUploadOptions options = new GridFSUploadOptions();
        options.chunkSizeBytes(358400);//定义chunk大小
        GridFSUploadStream stream = grid.openUploadStream("test.png",options); //创建上传流
        InputStream in = null;
        try{
            File file = new File("F:\\项目资料\\图片\\banner1.png");

            in = new FileInputStream(file);
            int tempbyte;

            while ((tempbyte = in.read()) != -1) {
                stream.write(tempbyte);
            }
            in.close();

            stream.close();
            System.out.println("文件id:"+stream.getFileId());
        }catch (IOException e){
            e.printStackTrace();
        }



    }


    // MongoDB GridFS  跟据文档id取图片
    @Test
    public void test2(HttpServletResponse resp){
        GridFSBucket grid = MongoDBUtil.getGrid();
        GridFSUploadOptions options = new GridFSUploadOptions();
        try{
            OutputStream out = resp.getOutputStream();
            grid.downloadToStream(new ObjectId("61c305e0136fb133fcf3f247"),out);

        }catch (IOException e){

        }

    }
}

 

 

 

五、推荐使用图形化工具 Robo 3T
下载地址 https://robomongo.org/download/
一键安装非常方便这里不赘述
操作界面如下:

 



posted @ 2021-12-31 18:04  采采卷耳&不盈倾筐  阅读(363)  评论(0编辑  收藏  举报