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进阶之路16  模块入门
			索引取值与迭代取值的差异 l1 = [11,22,33,44,55] 1.索引取值 可以任意位置任意次数取值 不支持无序类型的数据取值 2.迭代取值 只能从前往后依次取值无法后退 支持所有类型的数据取 ... 
- MySql树形结构(多级菜单)查询设计方案
			背景 又很久没更新了,很幸运地新冠引发了严重的上呼吸道感染,大家羊过后注意休息和防护 工作中(尤其是传统项目中)经常遇到这种需要,就是树形结构的查询(多级查询),常见的场景有:组织架构(用户部门)查询 ... 
- Ubuntu 安装 SSH
			sudo apt install openssh-server sudo systemctl status ssh sudo ufw allow ssh 
- 创建进程的多种方式、多进程实现TCP并发等知识点
			创建进程的多种方式.多进程实现TCP并发等知识点 一.同步与异步 1.提交完成任务之后原地等待任务的返回结果,期间不做任何事 2.提交完任务之后不愿原地等待任务的返回结果,直接去做其他事情,有结果自动 ... 
- python导入xls数据到db--优化版
			import sys from orator import DatabaseManager import xlrd dbconfig = { 'mysql': { 'driver': 'mysql', ... 
- java画海报
			package demotest; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; impor ... 
- Kinsoku jikou desu新浪股票接口变动
			1.问题原因 新浪股票接口返回如标题所示值:Kinsoku jikou desu! http://hq.sinajs.cn/list=code 新浪股票的接口变动,需要在请求头中添加Referer值. ... 
- .NET 8 预览版 1:NativeAOT 升级和新的Blazor United
			.NET团队 今天在官方博客上 发布了.NET 8的第一个预览版,.NET 8 是一个长期支持 (LTS) 版本[1],.NET 的版本包括产品.库.运行时和工具,是 Microsoft 内部和外部多 ... 
- gitbook使用指南
			一. node 下载 不要去node官网下载,那是最新版的,官方没提供旧版node.如果下载了最新版的还得下载一个管理node版本的工具,很麻烦且没必要. 在这个网站下载node:https://no ... 
- Spark系列 - (3) Spark SQL
			3. Spark SQL 3.1 Hive.Shark和Sparksql Hive:Hadoop刚开始出来的时候,使用的是hadoop自带的分布式计算系统 MapReduce,但是MapReduce的 ... 
