• JAVA MongoDB 连接以及增删改查


    pom.xml引入jar

            <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>bson</artifactId>
                <version>4.7.1</version>
            </dependency>
            <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>mongo-java-driver</artifactId>
                <version>3.8.2</version>
            </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    JAVA MongoApi 操作

    Java连接MongoDB

      public static void main(String[] args) {
            try {
                //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
                //ServerAddress()两个参数分别为 服务器地址 和 端口
                ServerAddress serverAddress = new ServerAddress("172.16.131.156",27017);
                List<ServerAddress> addrs = new ArrayList<ServerAddress>();
                addrs.add(serverAddress);
    
                //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
                MongoCredential credential = MongoCredential.createScramSha1Credential("tbook", "STC", "tbook".toCharArray());
    //            List credentials = new ArrayList();
    //            credentials.add(credential);
                MongoClientOptions.Builder build = new MongoClientOptions.Builder();
                build.connectionsPerHost(50); //与目标数据库能够建立的最大connection数量为50
                build.maxWaitTime(2*60*1000);
               ;
                build.threadsAllowedToBlockForConnectionMultiplier(50); //如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
                build.connectTimeout(1000*60*1); //与数据库建立连接的timeout设置为1分钟
                build.localThreshold(15000);
                build.maxConnectionIdleTime(6000);
                build.socketTimeout(60000);
                MongoClientOptions myOptions = build.build();
                //通过连接认证获取MongoDB连接
                MongoClient mongoClient = new MongoClient(addrs,credential,myOptions);
                //连接到数据库
                MongoDatabase mongoDatabase = mongoClient.getDatabase("STC");
                System.out.println("Connect to database successfully");
    //            insertWhere(mongoDatabase);
    //            query(mongoDatabase);
    //            queryWhere(mongoDatabase);
    //            insertWhere(mongoDatabase);
    //            updateWhere(mongoDatabase);
                findOneUpdate(mongoDatabase);
            } catch (Exception e) {
                System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    查询

    集合查询 find
    // table 为集合
    mongoDatabase.getCollection(table).find()
    
    • 1
    • 2
    查询集合的总数量 countDocuments
    // table 为集合
    mongoDatabase.getCollection(table).countDocuments()
    
    • 1
    • 2

    按条件查询

    单条件查询 Filters.eq
     Bson bson =  Filters.eq("name",1);
     mongoDatabase.getCollection(table).find(bson);
    
    • 1
    • 2
    单条件查询数量 countDocuments
    Bson bson =  Filters.eq("name",1);
     mongoDatabase.getCollection(table).countDocuments(bson);
    
    • 1
    • 2
    多条件查询 Filters.and
     Bson bson =Filters.and( Filters.eq("name",1), Filters.eq("_id",0));
     mongoDatabase.getCollection(table).find(bson);
    
    • 1
    • 2
    多条件查询数量 countDocuments
     Bson bson =Filters.and( Filters.eq("name",1), Filters.eq("_id",0));
     mongoDatabase.getCollection(table).countDocuments(bson);
    
    • 1
    • 2
    查询返回指定字段 projection
    Bson bson =Filters.and( Filters.eq("name",1), Filters.eq("_id",0));
    FindIterable<Document> tbook = mongoDatabase.getCollection(table).find().projection(bson);
    
    • 1
    • 2
    查询并排序 sort
    //-1 为倒序  1为正序
    Bson sort = Filters.eq("time",-1);
    FindIterable<Document> tbook1 = mongoDatabase.getCollection(table).find().sort(sort);
    
    • 1
    • 2
    • 3
    按条件,时间区间查询并排序
    // Filters.eq 条件匹配   Filters.gte  大于  Filters.lte  小于
    
    Bson filter =Filters.and(Filters.eq("securityID", "TS2306"),Filters.gte("createTime", "2022-10-19 00:00:00.000"),Filters.lte("createTime", "2022-10-19 23:59:59.999")) ;
    Bson sort = Filters.eq("time",-1);
    FindIterable<Document> tbook = mongoDatabase.getCollection(table).find(filter).sort(sort);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    模糊查询 regex
    Bson filter = Filters.regex("name", "小明");
    mongoDatabase.getCollection("test").find(filter);
    
    • 1
    • 2
    分页查询 skip,limit
    //skip 跳多少行,limit看多少数据
    Bson filter = Filters.regex("name", "小明");
    mongoDatabase.getCollection("test").find(filter).skip(2).limit(10);
    
    • 1
    • 2
    • 3

    添加

    单条添加 insertOne
    Document document = new Document();
    document.append("name","小明").append("age",10).append("sex","男").append("time","2022-10-18 17:45:06.465");
    mongoDatabase.getCollection("test").insertOne(documents);
    
    • 1
    • 2
    • 3
    多条添加 insertMany
    List<Document> documents = new ArrayList<>();
    Document document = new Document();
    document.append("name","小明").append("age",10).append("sex","男").append("time","2022-10-18 17:45:06.465");
    Document document1 = new Document();
    document1.append("name","小红").append("age",10).append("sex","女").append("time","2022-10-18 17:45:06.460");
    documents.add(document);
    documents.add(document1);
    mongoDatabase.getCollection("test").insertMany(documents);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    修改

    有就修改,没有就添加 findOneAndUpdate
    // true 为默认添加,false为不添加
    Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
    Document document = new Document();
    document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
    Document oneAndUpdate = mongoDatabase.getCollection("test").findOneAndUpdate(filter, new Document().append("$set", document), new FindOneAndUpdateOptions().upsert(true));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    修改单条 updateOne
    Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
    Document document = new Document();
    document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
    mongoDatabase.getCollection("test").updateOne(filter,new Document().append("$set", document));
    
    • 1
    • 2
    • 3
    • 4
    修改多条 updateMany
    Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
    Document document = new Document();
    document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
    mongoDatabase.getCollection("test").updateMany(filter,new Document().append("$set", document));
    
    • 1
    • 2
    • 3
    • 4

    删除数据

    删除单个数据 deleteOne
    Bson filter = Filters.and(Filters.eq("name", "小明"), Filters.eq("sex", "男"));
    mongoDatabase.getCollection("test").deleteOne(filter);
    
    • 1
    • 2
    删除多个数据 deleteMany
    Bson filter = Filters.and(Filters.eq("name", "小明"), Filters.eq("sex", "男"));
    mongoDatabase.getCollection("test").deleteMany(filter);
    
    • 1
    • 2

    JAVA代码展示

    package test;
    
    import com.mongodb.*;
    import com.mongodb.client.ClientSession;
    import com.mongodb.client.FindIterable;
    import com.mongodb.client.MongoDatabase;
    import com.mongodb.client.model.Filters;
    import com.mongodb.client.model.FindOneAndUpdateOptions;
    import com.mongodb.client.result.UpdateResult;
    import org.bson.Document;
    import org.bson.conversions.Bson;
    import org.bson.types.ObjectId;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.TimeUnit;
    
    public class Authentication {
        public static String table = "test";
        public static void main(String[] args) {
            try {
                //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
                //ServerAddress()两个参数分别为 服务器地址 和 端口
                ServerAddress serverAddress = new ServerAddress("172.16.131.156",27017);
                List<ServerAddress> addrs = new ArrayList<ServerAddress>();
                addrs.add(serverAddress);
    
                //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
                MongoCredential credential = MongoCredential.createScramSha1Credential("tbook", "STC", "tbook".toCharArray());
    //            List credentials = new ArrayList();
    //            credentials.add(credential);
                MongoClientOptions.Builder build = new MongoClientOptions.Builder();
                build.connectionsPerHost(50); //与目标数据库能够建立的最大connection数量为50
                build.maxWaitTime(2*60*1000);
               ;
                build.threadsAllowedToBlockForConnectionMultiplier(50); //如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
                build.connectTimeout(1000*60*1); //与数据库建立连接的timeout设置为1分钟
                build.localThreshold(15000);
                build.maxConnectionIdleTime(6000);
                build.socketTimeout(60000);
                MongoClientOptions myOptions = build.build();
                //通过连接认证获取MongoDB连接
                MongoClient mongoClient = new MongoClient(addrs,credential,myOptions);
                //连接到数据库
                MongoDatabase mongoDatabase = mongoClient.getDatabase("STC");
                System.out.println("Connect to database successfully");
    //            insertWhere(mongoDatabase);
    //            query(mongoDatabase);
    //            queryWhere(mongoDatabase);
    //            insertWhere(mongoDatabase);
    //            updateWhere(mongoDatabase);
                findOneUpdate(mongoDatabase);
            } catch (Exception e) {
                System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            }
        }
    
        //查询
        public static void query(MongoDatabase mongoDatabase){
            mongoDatabase.getCollection(table).countDocuments();
            Bson bson =Filters.and( Filters.eq("name",1), Filters.eq("_id",0));
    
            FindIterable<Document> tbook = mongoDatabase.getCollection(table).find().projection(bson);
            tbook.forEach((Block<? super Document>) document -> {
                System.out.println(document.get("name"));
            });
            Bson sort = Filters.eq("time",-1);
            FindIterable<Document> tbook1 = mongoDatabase.getCollection(table).find().sort(sort);
            tbook1.forEach((Block<? super Document>) document -> {
                System.out.println(document);
            });
        }
    
        //条件查询
        public static void queryWhere(MongoDatabase mongoDatabase){
            Bson filter =Filters.and(Filters.eq("securityID", "TS2306"),
                    Filters.gte("createTime", "2022-10-19 00:00:00.000"),
                    Filters.lte("createTime", "2022-10-19 23:59:59.999")) ;
            Bson sort = Filters.eq("time",-1);
            FindIterable<Document> tbook = mongoDatabase.getCollection(table).find(filter).sort(sort);
            long countDocuments = mongoDatabase.getCollection(table).countDocuments(filter);
            System.out.println(countDocuments);
            tbook.forEach((Block<? super Document>) document -> {
                System.out.println(document);
            });
        }
    
        //条件查询
        public static void updateWhere(MongoDatabase mongoDatabase){
            Bson filter =Filters.and(Filters.eq("_id", new ObjectId("63579bcd4d01156a58abfc1e"))) ;
            Document document = new Document();
            document.append("name","小小红").append("age",10).append("sex","女");
            UpdateResult updateResult = mongoDatabase.getCollection("test").updateOne(filter,  new Document("$set", document));
                System.out.println(updateResult.getModifiedCount());
        }
        //条件查询
        public static void findOneUpdate(MongoDatabase mongoDatabase){
            Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
            Document document = new Document();
            document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
            Document oneAndUpdate = mongoDatabase.getCollection("test").findOneAndUpdate(filter, new Document().append("$set", document), new FindOneAndUpdateOptions().upsert(true));
            mongoDatabase.getCollection("test").updateMany(filter,new Document().append("$set", document));
            System.out.println(oneAndUpdate);
        }
    
        //修改
        public static void updateOneMany(MongoDatabase mongoDatabase){
            Bson filter =Filters.and(Filters.eq("name", "小明"),Filters.eq("sex","男")) ;
            Document document = new Document();
            document.append("name","小明军").append("age",15).append("sex","男人").append("time","2022-10-18 17:45:06.480");
            mongoDatabase.getCollection("test").updateMany(filter,new Document().append("$set", document));
            mongoDatabase.getCollection("test").updateOne(filter,new Document().append("$set", document));
        }
    
        //修改
        public static void deleteOneMany(MongoDatabase mongoDatabase) {
            Bson filter = Filters.and(Filters.eq("name", "小明"), Filters.eq("sex", "男"));
            mongoDatabase.getCollection("test").deleteMany(filter);
            mongoDatabase.getCollection("test").deleteOne(filter);
        }
    
        //模糊查询
        public static void likeQuery(MongoDatabase mongoDatabase) {
            Bson filter = Filters.regex("name", "小明");
            mongoDatabase.getCollection("test").find(filter).skip(2).limit(10);
            mongoDatabase.getCollection("test").find(filter);
        }
    
        //条件查询
        public static void insertWhere(MongoDatabase mongoDatabase){
            List<Document> documents = new ArrayList<>();
            Document document = new Document();
            document.append("name","小明").append("age",10).append("sex","男").append("time","2022-10-18 17:45:06.465");
            Document document1 = new Document();
            document1.append("name","小红").append("age",10).append("sex","女").append("time","2022-10-18 17:45:06.460");
            documents.add(document);
            documents.add(document1);
            mongoDatabase.getCollection("test").insertMany(documents);
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
  • 相关阅读:
    Python---类的定义和使用语法
    2021美亚团队赛复盘
    【从零开始的Java开发】2-9-2 案例:仿Windows计算器
    K8S | Service服务发现
    GIT 分支管理办法
    Java:开始Java编程生涯的小指南
    CSP-J1 CSP-S1 初赛模拟题试卷整理2022.08.24
    Linux添加root权限:is not in the sudoers file解决方法
    【数据结构】 Map和Set详解
    【Ubuntu】Ubuntu 20.04安装
  • 原文地址:https://blog.csdn.net/qq_27566167/article/details/127682761