java MongoDB 测试demo

java MongoDB 测试demo 工具包

/**
 * 描述:
 * MongoDB 测试demo 工具包
 * @author 闲走天涯
 * @create 2021/7/22 15:09
 */
public class MongoDBJDBC {
    private static String host="localhost";
    private static Integer port = 27017;

    /**
     * 连接 数据库
     * @param dbName
     * @return
     */
    public static MongoDatabase connect(String dbName){
        try {
            if(strIsNull(dbName)){
                return null;
            }
            // 连接到 MongoDB服务
            MongoClient mongoClient = new MongoClient(host, port);
            String point = mongoClient.getConnectPoint();
            System.out.println("point="+point);
            //连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
            System.out.println("connent to MongoDB database "+dbName+" successfully");
            return mongoDatabase;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 连接 数据库
     * 认证用户名密码
     * @param username
     * @param password
     * @param dbName
     * @return
     */
    public static MongoDatabase connect(String username,String password,String dbName){
        try {
            if(strIsNull(dbName) && strIsNull(username) && strIsNull(password)){
                return null;
            }
            //连接到MongoDB服务
            ServerAddress serverAddress = new ServerAddress(host,port);
            List<ServerAddress> addressList = new ArrayList<>();
            addressList.add(serverAddress);
            // MongoCredential 三个参数分别为用户名,数据库名,密码
            //连接认证信息
            MongoCredential credential = MongoCredential.createScramSha1Credential(username,dbName,password.toCharArray());
            List<MongoCredential> credentialList = new ArrayList<>();
            credentialList.add(credential);
            //通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(addressList,credentialList);
            String point = mongoClient.getConnectPoint();
            System.out.println("point="+point);
            //连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
            System.out.println("connent to MongoDB database "+dbName+" successfully");
            return mongoDatabase;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static BasicDBObject orderBy(String order,ByUnit by){
        BasicDBObject sort = new BasicDBObject();
        sort.put(order,by.getBy());
        return sort;
    }

    /**
     * 判断字符串是否为空
     * @param str
     * @return
     */
    public static boolean strIsNull(String str){
        return !(str!=null && !"".equals(str));
    }

    public static void main(String[] args) {
        MongoDatabase mongoDatabase = MongoDBJDBC.connect("test","123456","test");
        MongoCollection<Document> collection = mongoDatabase.getCollection("runoob");

        //集合-》查询
        FindIterable<Document> findIterable = null;
        //查询所有
        findIterable = collection.find();
        //使用正则表达式查询
        findIterable = collection.find(Filters.regex("name","/菜鸟/"));

        //使用条件查询
        //匹配小于20
        findIterable = collection.find(Filters.lt("age",20));
        //匹配小于或等于
        findIterable = collection.find(Filters.lte("age",20));
        //匹配等于
        findIterable = collection.find(Filters.eq("age",15));
        //匹配大于20
        findIterable = collection.find(Filters.gt("age",10));
        //匹配大于或等于
        findIterable = collection.find(Filters.gte("age",10));
        //匹配数组中指定的值
        findIterable = collection.find(Filters.in("age",10));
        //不匹配数组中任何指定的任何值=> not in
        findIterable = collection.find(Filters.nin("age",10));
        //匹配不等于指定值的值
        findIterable = collection.find(Filters.ne("age",10));

        //条件组合- 与
        findIterable = collection.find(Filters.and(Filters.regex("name","/菜鸟/"),Filters.lt("age","20")));
        //条件组合- 或
        findIterable = collection.find(Filters.or(Filters.regex("name","/菜鸟/"),Filters.lt("age","20")));
        //条件组合- 非 (单个子句/条件)
        findIterable = collection.find(Filters.not(Filters.regex("name","/菜鸟/")));
        //条件组合- 非 (多个子句/条件)
        findIterable = collection.find(Filters.or(Filters.regex("name","/菜鸟/"),Filters.lt("age","20")));

        //查询是否存在的值 true=存在(默认),false=不存在
        findIterable = collection.find(Filters.exists("age"));//查询存在 默认存在
        findIterable = collection.find(Filters.exists("age",false));//查询不存在 true=存在 ,false=不存在

        //查询匹配类型的值,例如 匹配name为string类型的值
        findIterable = collection.find(Filters.type("name",BsonType.STRING));

        // 排序 按照字段
        findIterable = collection.find().sort(MongoDBJDBC.orderBy("age",ByUnit.DESC));
        //限制条数
        findIterable = collection.find().limit(2);
        //从下标数开始 例如 从下标为2,即第三个开始
        findIterable = collection.find().skip(2);
        //分页 limit=2 限制每页条数为2 skip=2=2*1 从第2页开始即第三个开始(页码*页数=记录的下标数)
        // 相当于 SELECT * FROM table LIMIT 2,2;//查询第3-4行记录
        findIterable = collection.find().sort(MongoDBJDBC.orderBy("age",ByUnit.DESC)).limit(2).skip(2);

        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()){
            Document document = mongoCursor.next();
            Object o = document.entrySet();
            Object values = document.values();
            JSONObject json = JSONObject.parseObject(document.toJson());
            System.out.println(document);
        }


    }

}

/**
 * 枚举类型
 * 排序asc/desc
 */
enum ByUnit{
    ASC(1),
    DESC(-1);

    private Integer by;
    ByUnit(Integer by){
        this.by=by;
    }

    public Integer getBy() {
        return by;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaMongoDB的结合是一种常见的开发方式,可以使用Java驱动程序连接和操作MongoDB数据库。以下是一些关于JavaMongoDB的常见问题和答案: 1. 如何在Java中连接MongoDB数据库? 使用Java连接MongoDB需要导入MongoDBJava驱动程序。你可以在Maven或Gradle项目中添加以下依赖关系: ```xml <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.7</version> </dependency> ``` 然后,你可以使用以下代码连接到MongoDB: ```java MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase database = mongoClient.getDatabase("mydb"); ``` 这是一个简单的连接示例,其中"localhost"是MongoDB服务器的主机名,27017是默认端口,"mydb"是要连接的数据库名称。 2. 如何在Java中插入数据到MongoDB? 使用JavaMongoDB插入数据很简单。以下是一个示例代码: ```java MongoCollection<Document> collection = database.getCollection("mycollection"); Document document = new Document("name", "John") .append("age", 30) .append("city", "New York"); collection.insertOne(document); ``` 这个示例将在名为"mycollection"的集合中插入一个文档。 3. 如何在Java查询MongoDB中的数据? 使用Java查询MongoDB也很简单。以下是一个示例代码: ```java MongoCollection<Document> collection = database.getCollection("mycollection"); Document query = new Document("name", "John"); FindIterable<Document> results = collection.find(query); for (Document document : results) { System.out.println(document); } ``` 这个示例将查询名为"John"的所有文档,并将结果打印到控制台。 4. 如何在Java中更新MongoDB中的数据? 使用Java更新MongoDB的数据也很简单。以下是一个示例代码: ```java Mongo

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值