zoukankan      html  css  js  c++  java
  • Java 链接mongodb 执行集合查询

    public static String mongodbConnection(String phone){
            String sendCode = null;
            //创建mongodb链接地址
            MongoClientURI uri = new MongoClientURI(properties.getProperty("mongodb.url"));
            //链接mongodb数据库
            MongoClient client = new MongoClient(uri);
            // 连接到数据库
            MongoDatabase db = client.getDatabase(properties.getProperty("mongodb.dataBaseName"));
            // 获取send_record集合
            MongoCollection collection = db.getCollection("send_record");
            //查询条件,模糊查询
            Pattern pattern = Pattern.compile(phone);
            BasicDBObject cond = new BasicDBObject();
            cond.put("phone",new BasicDBObject("$regex",pattern));
            //执行查询
            MongoCursor<Document> cursor = collection.find(cond).iterator();
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            while (cursor.hasNext()){
                System.out.println(cursor.next());
                //map集合处理查询结果
                Map<String, Object> map = new HashMap<String, Object>();
                map.putAll(cursor.next());
                list.add(map);
                String regEx="[^0-9]";
                Pattern p = Pattern.compile(regEx);
                System.out.println(map.get("content").toString());
                //正则获取文本中的数字
                sendCode = p.matcher(map.get("content").toString()).replaceAll("").trim();
            }
            return sendCode;
        }
    <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>mongo-java-driver</artifactId>
                <version>3.10.2</version>
     </dependency>
    执行结果
    Document{{_id=5dc5279739ebb45bd97c495a, country_code=+86, phone=18680362285, content=您的验证码是559494。请不要把验证码泄露给其他人。如非本人操作,请及时修改密码以防被盗!, status=1, remark={"code":"0","msg":"SUCCESS","batchId":"5v6X312"}, last_update_time=Fri Nov 08 16:30:15 CST 2019, created=Fri Nov 08 16:30:15 CST 2019, _class=com.blockeng.repository.SendRecord}}
    您的验证码是394588。请不要把验证码泄露给其他人。如非本人操作,请及时修改密码以防被盗!
    394588
  • 相关阅读:
    Linux三剑客之sed深度实践讲解(上)
    Linux第三阶段题型测试
    Linux正则表达式题型
    linux文本处理三剑客命令及用法
    SSH服务协议、部署ssh、scp、sftp服务
    NFS客户端挂载及永久生效
    SSH实现无密码登录
    NFS深度解析及搭建同步NFS服务
    NFS文件系统及搭建NFS共享服务
    Linux系统磁盘管理
  • 原文地址:https://www.cnblogs.com/dwdw/p/12016571.html
Copyright © 2011-2022 走看看