引入mongo-java-driver-3.0.4 jar

工具类

//mongodb 连接数据库工具类
public class MongoDBUtil {
//不通过认证获取连接数据库对象
public static MongoDatabase getConnect(String database){
//连接到 mongodb 服务
MongoClient mongoClient = new MongoClient("localhost", 27017);

//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase(database);

//返回连接数据库对象
return mongoDatabase;
}

//需要密码认证方式连接
public static MongoDatabase getConnect2(String database){
List<ServerAddress> adds = new ArrayList<ServerAddress>();
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
adds.add(serverAddress);

List<MongoCredential> credentials = new ArrayList<MongoCredential>();
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
credentials.add(mongoCredential);

//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(adds, credentials);

//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase(database);

//返回连接数据库对象
return mongoDatabase;
}
}

条件查询

HashMap<String, Object> resultMap = new HashMap<String, Object>();
List<Document> result = new ArrayList<Document>();
MongoCollection<Document> collection = MongoDBUtil.getConnect("ccbfw").getCollection("fwpolicy");
Bson findQuery = null;
if (StringUtils.isNotBlank(page.getDevice_name() == null ? "" : page.getDevice_name())) {
Bson deviceName = Filters.and(deviceNameCondition(page.getDevice_name().trim()));
if (findQuery != null) {
findQuery = Filters.and(findQuery, Filters.and(deviceName));
} else {
findQuery = Filters.and(deviceName);
}
}
if (StringUtils.isNotBlank(page.getPolicy_id() == null ? "" : page.getPolicy_id())) {
Bson policyId = Filters.and(policyIdCondition(page.getPolicy_id().trim()));
if (findQuery != null) {
findQuery = Filters.and(findQuery, Filters.and(policyId));
} else {
findQuery = Filters.and(policyId);
}

}
if (StringUtils.isNotBlank(page.getService() == null ? "" : page.getService())) {
Set set = new HashSet();
//模糊匹配
Pattern pattern = Pattern.compile("^.*" + page.getService().trim() + ".*$", Pattern.CASE_INSENSITIVE);
set.add(pattern);
Bson service = Filters.in("service",set);
if (findQuery != null) {
findQuery = Filters.and(findQuery, Filters.and(service));
} else {
findQuery = Filters.and(service);
}
}
if (StringUtils.isNotBlank(page.getSource_address() == null ? "" : page.getSource_address())) {
Set set = new HashSet();
//模糊匹配
Pattern pattern = Pattern.compile("^.*" + page.getSource_address().trim() + ".*$", Pattern.CASE_INSENSITIVE);
set.add(pattern);
Bson source_address = Filters.in("source_address",set);
if (findQuery != null) {
findQuery = Filters.and(findQuery, Filters.and(source_address));
} else {
findQuery = Filters.and(source_address);
}
}
if (StringUtils.isNotBlank(page.getDest_address() == null ? "" : page.getDest_address().trim())) {
Set set = new HashSet();
//模糊匹配
Pattern pattern = Pattern.compile("^.*" + page.getDest_address().trim() + ".*$", Pattern.CASE_INSENSITIVE);
set.add(pattern);
Bson dest_address = Filters.in("dest_address", set);
if (findQuery != null) {
findQuery = Filters.and(findQuery, Filters.and(dest_address));
} else {
findQuery = Filters.and(dest_address);
}
}

MongoCursor<Document> cursor = null;
if (findQuery != null) {
cursor = collection.find(findQuery).sort(new Document("_id", -1)).skip(page.getFirstPage())
.limit(page.getRows()).iterator();
resultMap.put("total", collection.count(findQuery));
} else {
cursor = collection.find().sort(new Document("_id", -1)).skip(page.getFirstPage()).limit(page.getRows())
.iterator();
resultMap.put("total", collection.count());
}
try {
while (cursor.hasNext()) {
Document item = cursor.next();
result.add(item);
// System.out.println(item.toJson());

}
} finally {
cursor.close();// must be
}
resultMap.put("rows", result);
String json = Json.toJson(resultMap, JsonFormat.compact());

文档元素为数组的条件 匹配

int ipInt=IpTest.ipToInt(page.getSource_address().trim());
Bson condition_start=Filters.and(Filters.lte("startIp", ipInt));
Bson condition_end=Filters.and(Filters.gte("endIp", ipInt));
Bson condition=Filters.elemMatch("source_address", Filters.and(condition_start,condition_end));
if (findQuery != null) {
findQuery = Filters.and(findQuery,condition);
} else {
findQuery = Filters.and(condition);
}

JAVA操作Mongo 数组模糊查询的更多相关文章

  1. java操作elasticsearch实现前缀查询、wildcard、fuzzy模糊查询、ids查询

    1.前缀查询(prefix) //prefix前缀查询 @Test public void test15() throws UnknownHostException { //1.指定es集群 clus ...

  2. java操作elasticsearch实现条件查询(match、multiMatch、term、terms、reange)

    1.条件match query查询 //条件查询match query @Test public void test10() throws UnknownHostException { //1.指定e ...

  3. Java数据库学习之模糊查询(like )

    Java数据库学习之模糊查询(like ): 第一种方式:直接在SQL语句中进行拼接,此时需要注意的是parm在SQL语句中需要用单引号拼接起来,注意前后单引号之间不能空格 String sql = ...

  4. java使用elasticsearch进行模糊查询-已在项目中实际应用

    java使用elasticsearch进行模糊查询 使用环境上篇文章本人已书写过,需要maven坐标,ES连接工具类的请看上一篇文章,以下是内容是笔者在真实项目中运用总结而产生,并写的是主要方法和思路 ...

  5. php提供一维数组模糊查询

    2019年9月30日14:36:15 提供一维数组模糊查询,只支持utf-8 内部处理是Unicode 编码特殊编码格式的可能会出错 if (!function_exists('arrayFuzzyQ ...

  6. java操作elasticsearch实现聚合查询

    1.max 最大值 //max 求最大值 @Test public void test30() throws UnknownHostException{ //1.指定es集群 cluster.name ...

  7. java使用elasticsearch进行模糊查询之must使用-项目中实际使用

    java使用elasticsearch进行多个条件模糊查询 文章说明: 1.本篇文章,本人会从java连接elasticsearch到查询结果生成并映射到具体实体类(涵盖分页功能) 2.代码背景:el ...

  8. python 操作mongodb数据库模糊查询

    # -*- coding: utf-8 -*-import pymongoimport refrom pymongo import MongoClient #创建连接#10.20.66.106clie ...

  9. java~springboot~ibatis数组in查询的实现

    在ibatis的xml文件里,我们去写sql语句,对应mapper类的方法,这些sql语句与控制台上没什么两样,但在有些功能上需要注意,如where in这种从数组里查询符合条件的集合里,需要在xml ...

  10. 如何在java List中进行模糊查询

    比如我有下面这样一个List,里面存放的是多个Employee对象.然后我想对这个List进行按照Employee对象的名字进行模糊查询.有什么好的解决方案么? 比如我输入的查询条件为“wang”,那 ...

随机推荐

  1. Gvim基础操作(正则表达式)-02

    Gvim正则表达式 正则表达式在linux中使用非常广泛.主要是进行一些替换,在编写脚本的时候都会使用到.gvim.perl.sed.tcl中都会使用到. Gvim正则表达式的使用 搜索命令 /正则表 ...

  2. liunx系统安装JDK环境详细步骤

    Liunx系统安装JDK环境详细步骤 一 下载liunx版本jdk压缩包 进入JDK官方网站下载jdk压缩包.下载前需要登入账户,可以自己注册一个账户! 也可以使用本博主提供的网盘下载https:// ...

  3. 线上代码已变更,客户没有刷新浏览器,导致点击菜单后找不到相对路由js文件无法加载XXX路由,解决办法如下

    1,reload 方法,该方法强迫浏览器刷新当前页面. 语法:location.reload([bForceGet]) 参数: bForceGet, 可选参数, 默认为 false,从客户端缓存里取当 ...

  4. (原创)【B4A】一步一步入门01:简介、开发环境搭建、HelloWorld

    一.前言 作者注:絮絮叨叨,可跳过不看. 一直有开发跨平台软件的需求.因为我的主力是C# ,所以当MAUI出现后,我欣喜若狂的开始学习研究.但是经历了两个月左右的时间,我弃坑了,我发现MAUI不是我能 ...

  5. avalonia实现自定义小弹窗

    对于使用avalonia的时候某些功能需要到一些提示,比如异常或者成功都需要对用户进行提示,所以需要单独实现弹窗功能,并且可以自定义内部组件,这一期将手动实现一个简单的小弹窗,并且很容易自定义 创建项 ...

  6. 以交互的方式升级ESXi主机

    以交互的方式升级ESXi主机 环境说明: 需求:要将 ESXi 6.0 主机和 ESXi 6.5 主机升级到 ESXi 6.7,可从 CD.DVD 或 USB 闪存驱动器引导 ESXi 安装程序. 注 ...

  7. mysql15 sql优化-小表驱动大表 IN和EXITS

    转:https://blog.csdn.net/qq_27409289/article/details/85963089 1.IN查询分析 select * from a  where a.id in ...

  8. 打开MASA Blazor的正确姿势2:组件总览

    官网文档按拼音罗列组件,且部分嵌套组件没有在导航栏内列出,不利于浏览查阅.本篇文章的主要目的,主要是对所有组件按大家习惯的方式进行分类,简要介绍组件,并建立跳转官方文档的链接.   一.导航布局类 1 ...

  9. Docker安装Tomcat应用服务器

    1.安装镜像 1. Install the image: 可以先到https://hub.docker.com/  搜索镜像 You can get there first. https://hub. ...

  10. uboot之顶层Makefile

    uboot版本信息 VERSION = 2006 主版本号 PATCHLEVEL = 03 补丁版本号 SUBLEVEL = 次此版本号 EXTRAVERSION =  附加版本 NAME      ...