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