JAVA操作Mongo 数组模糊查询
引入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 数组模糊查询的更多相关文章
- java操作elasticsearch实现前缀查询、wildcard、fuzzy模糊查询、ids查询
1.前缀查询(prefix) //prefix前缀查询 @Test public void test15() throws UnknownHostException { //1.指定es集群 clus ...
- java操作elasticsearch实现条件查询(match、multiMatch、term、terms、reange)
1.条件match query查询 //条件查询match query @Test public void test10() throws UnknownHostException { //1.指定e ...
- Java数据库学习之模糊查询(like )
Java数据库学习之模糊查询(like ): 第一种方式:直接在SQL语句中进行拼接,此时需要注意的是parm在SQL语句中需要用单引号拼接起来,注意前后单引号之间不能空格 String sql = ...
- java使用elasticsearch进行模糊查询-已在项目中实际应用
java使用elasticsearch进行模糊查询 使用环境上篇文章本人已书写过,需要maven坐标,ES连接工具类的请看上一篇文章,以下是内容是笔者在真实项目中运用总结而产生,并写的是主要方法和思路 ...
- php提供一维数组模糊查询
2019年9月30日14:36:15 提供一维数组模糊查询,只支持utf-8 内部处理是Unicode 编码特殊编码格式的可能会出错 if (!function_exists('arrayFuzzyQ ...
- java操作elasticsearch实现聚合查询
1.max 最大值 //max 求最大值 @Test public void test30() throws UnknownHostException{ //1.指定es集群 cluster.name ...
- java使用elasticsearch进行模糊查询之must使用-项目中实际使用
java使用elasticsearch进行多个条件模糊查询 文章说明: 1.本篇文章,本人会从java连接elasticsearch到查询结果生成并映射到具体实体类(涵盖分页功能) 2.代码背景:el ...
- python 操作mongodb数据库模糊查询
# -*- coding: utf-8 -*-import pymongoimport refrom pymongo import MongoClient #创建连接#10.20.66.106clie ...
- java~springboot~ibatis数组in查询的实现
在ibatis的xml文件里,我们去写sql语句,对应mapper类的方法,这些sql语句与控制台上没什么两样,但在有些功能上需要注意,如where in这种从数组里查询符合条件的集合里,需要在xml ...
- 如何在java List中进行模糊查询
比如我有下面这样一个List,里面存放的是多个Employee对象.然后我想对这个List进行按照Employee对象的名字进行模糊查询.有什么好的解决方案么? 比如我输入的查询条件为“wang”,那 ...
随机推荐
- [常用工具] Python视频解码库DeFFcode使用指北
DeFFcode是一种跨平台的高性能视频帧解码器,通过内部封装ffmpeg,提供GPU解码支持,几行python代码就能够快速解码视频帧,并具有强大的错误处理能力.DeFFcode的APIs支持多种媒 ...
- 写一个 Markdown 博客客户端
这个"伪需求"是最近才想到的. 关于文章管理的想法,说来话长.我最初是在 CSDN 写技术文章,就用网页上的编辑器.后来在 CppBlog 写,用上了 Windows Live W ...
- Mac上优秀的虚拟机软件推荐 PD Parallels Desktop 18.1.1
APPERK 软件信息 软件名称 ParallelsDesktop 版本号 18.1.1 软件类型 官网版 + 商业版 安装包大小 390MB 语言 中文 系统支持 macOS11及以上(M芯片原生) ...
- 阿里云kafka使用记录(python版本)
kafka端 consumer vpc版代码 import socket from kafka import KafkaConsumer from kafka.errors import Ka ...
- 基于WebSocket的实时消息传递设计
目录 概述 整体架构 设计 流程设计 程序设计 WebSocketServer 概述 新增pom 新增配置类 创建websocket端点 WebSocketClient 概述 安装WebSocketS ...
- 定时调度插件------Quartz.NET(一)
官网地址 https://www.quartz-scheduler.net/ 使用说明 dll引用 使用NuGet 搜索Quartz,作者为Marko Lahma, Quartz.NET为该插件 目前 ...
- Pytest插件pytest-assume多重断言
Pytest插件pytest-assume多重断言 背景 import pytest def test_assume1(): assert 1 == 2 print('hello') assert 2 ...
- 基于Apache Hudi 构建Serverless实时分析平台
NerdWallet 的使命是为生活中的所有财务决策提供清晰的信息. 这涵盖了一系列不同的主题:从选择合适的信用卡到管理您的支出,到找到最好的个人贷款,再到为您的抵押贷款再融资. 因此,NerdWal ...
- spring cloud alibaba Nacos集群部署 Linux
参考:https://www.cnblogs.com/dw3306/p/12961353.html 1.官网: https://nacos.io/zh-cn/docs/cluster-mode- ...
- C#获取html标签内容的方法
C# 获取html标签内容的方法: /// <summary> /// 获取html网页标签内容 /// 例如:<span class="index_infoItem__E ...