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
  • 相关阅读:
    Method of Four Russians 学习笔记
    一道不知道哪里来的数论题
    ICPC2021银川 游记
    决策单调性优化dp学习笔记
    浅谈如何优美地实现线段树?
    2021 EC Final 2020 题解
    5.5 SYSU校内训练
    5.4 SYSU校内训练
    存储相关招聘信息-长期
    screen几个使用方法
  • 原文地址:https://www.cnblogs.com/dwdw/p/12016571.html
Copyright © 2011-2022 走看看