spring data mongodb之mongodbTemplate查询总结

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 常用的列表查询(筛选条件,查询字段,排序及分页),相当于关系型数据库的:select fields from tableName where coditions order by field skip limit;DBObject cond = new BasicDBObject();//等于条件cond.

常用的列表查询(筛选条件,查询字段,排序及分页),相当于关系型数据库的:

select fields from tableName where coditions order by field skip limit;
DBObject cond = new BasicDBObject();
//等于条件
cond.put("sex","male");
//非等于条件
cond.put("age", new BasicDBObject(QueryOperators.GTE,20)
            .append(QueryOperators.LTE,30));
//添加or条件(和上面的条件还是and关系)
BasicDBList orList = new BasicDBList();
DBObject orCond1 = new BasicDBObject();
orCond1.put("name", "lisi");
DBObject orCond2 = new BasicDBObject();
orCond2.put("name", "zhaoliu");
orList.add(orCond1);
orList.add(orCond2);
cond.put(QueryOperators.OR, orList);
//限制查询返回的字段
DBObject feild = new BasicDBObject();
feild.put("name", 1);//查询name
feild.put("_id", 0);//_id不查询
Query query = new BasicQuery(cond,feild);
//单字段倒序
query.with(new Sort(Direction.DESC,"age"));
//多字段排序
/*List<Order> orders = new ArrayList<Sort.Order>();
orders.add(new Order(Direction.DESC,"age"));
orders.add(new Order(Direction.ASC,"name"));
query.with(new Sort(orders));*/
//分页
query.skip(0).limit(10);
List<HashMap> result = mongoTemplate.find(query, HashMap.class,"person");

QueryOperators常用的比较符:

OR = "$or"or条件
AND = "$and"and条件
GT = "$gt":大于操作
GTE = "$gte":大于等于操作
LT = "$lt":小于操作
LTE = "$lte"小于等于操作
NE = "$ne":不等于操作
IN = "$in"in操作

//示例
BasicDBList fieldList = new BasicDBList();
fieldList.add("上海");
cond.put("province", new BasicDBObject(QueryOperators.IN,fieldList));

NIN = "$nin"not in
MOD = "$mod";

//示例(age和6取模为0的数据)
BasicDBList modList = new BasicDBList();
modList.add(6);
modList.add(0);
cond.put("age", new BasicDBObject(QueryOperators.MOD,modList));

ALL = "$all":字段同时满足all中的所有条件,可以和$elemMatch配合使用
SIZE = "$size":数组的长度
EXISTS = "$exists":字段是否存在筛选(true,false)
ELEM_MATCH = "$elemMatch":内嵌文档完全匹配查询
WHERE = "$where"where条件,一般用于文档中两个字段的比较

//示例(name字段的值和province的值不等的数据)
cond.put(QueryOperators.WHERE,"this.name != this.province");

NOR = "$nor":同时不满足
TYPE = "$type":字段类型匹配
//模糊查询
cond.put("province", new BasicDBObject("$regex","^.*上.*$"));
NOT = "$not":不满足指定条件,或者该字段不存在
ORDER_BY = "$orderby":添加排序字段

这里列出的是比较常用的一些操作符,还有一些比较复杂的(例如计算点一点之间距离条件的)请参考:

使用游标的方式进行分页查询:

DBObject cond = new BasicDBObject();
//等于条件
cond.put("sex","male");
//非等于条件
cond.put("age", new BasicDBObject(QueryOperators.GTE,20)
            .append(QueryOperators.LTE,30));
//添加or条件(和上面的条件还是and关系)
BasicDBList orList = new BasicDBList();
DBObject orCond1 = new BasicDBObject();
orCond1.put("name", "lisi");
DBObject orCond2 = new BasicDBObject();
orCond2.put("name", "zhaoliu");
orList.add(orCond1);
orList.add(orCond2);
cond.put(QueryOperators.OR, orList);
//限制查询返回的字段
DBObject feild = new BasicDBObject();
feild.put("name", 1);//查询name
feild.put("_id", 0);//_id不查询
//排序字段
DBObject order = new BasicDBObject();
order.put("age",1);
DBCursor dbCursor = mongoTemplate.getCollection("person").find(cond, feild).sort(order).skip(0).limit(10);
System.err.println(dbCursor.count());
System.err.println(dbCursor.toArray());

根据某字段去重查询:

DBObject cond = new BasicDBObject();
cond.put("sex","male");
List distinct = mongoTemplate.getCollection("person").distinct("name",cond);

根据查询条件查询条数:

DBObject cond = new BasicDBObject();
cond.put("sex","male");
long count = mongoTemplate.getCollection("person").count(cond);
System.out.println(count);

使用Aggregation Pipeline进行聚群分析:

List<AggregationOperation> aggregationOptions = new ArrayList<AggregationOperation>();      aggregationOptions.add(Aggregation.match(Criteria.where("province").is("上海")));     aggregationOptions.add(Aggregation.group("age").count().as("count"));
aggregationOptions.add(Aggregation.project("count").and("age").previousOperation().andExclude("_id"));
aggregationOptions.add(Aggregation.sort(Direction.DESC,"age"));
aggregationOptions.add(Aggregation.skip(0L));
aggregationOptions.add(Aggregation.limit(10));
Aggregation agg = Aggregation.newAggregation(aggregationOptions);
AggregationResults<HashMap> aggregate = mongoTemplate.aggregate(agg,"person", HashMap.class);
List<HashMap> mappedResults = aggregate.getMappedResults();

其中group后可以添加一些聚合函数,如sum,avg等。如果遇到内嵌文档,需要拆分的情况,我们可以使用unwind将内嵌文档进行拆分:

aggregationOptions.add(Aggregation.unwind(field));
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
4月前
|
druid Java 数据库连接
SpringBoot原理分析 | Spring Data整合:JDBC、Druid、Mybatis
SpringBoot原理分析 | Spring Data整合:JDBC、Druid、Mybatis
63 0
|
4月前
|
NoSQL Java MongoDB
Spring Boot中MongoDB的使用和实战
Spring Boot中MongoDB的使用和实战
63 0
|
4月前
|
XML Java 数据库连接
Spring Boot的数据访问之Spring Data JPA以及Hibernate的实战(超详细 附源码)
Spring Boot的数据访问之Spring Data JPA以及Hibernate的实战(超详细 附源码)
47 0
|
3月前
|
NoSQL 关系型数据库 MySQL
深入了解 Python MongoDB 查询:find 和 find_one 方法完全解析
在 MongoDB 中,我们使用 find() 和 find_one() 方法来在集合中查找数据,就像在MySQL数据库中使用 SELECT 语句来在表中查找数据一样
65 1
|
4月前
|
Java Spring
Spring Boot利用Spring Data JPA实现排序与分页查询实战(附源码,超详细)
Spring Boot利用Spring Data JPA实现排序与分页查询实战(附源码,超详细)
77 0
|
16天前
|
JSON NoSQL MongoDB
mongodb导出聚合查询的数据
mongodb导出聚合查询的数据
|
1月前
|
前端开发 Java Spring
Java 新手如何使用Spring MVC 中的查询字符串和查询参数
Java 新手如何使用Spring MVC 中的查询字符串和查询参数
|
1月前
|
Java 数据库 Spring
如何使用Spring Data JPA完成审计功能
如何使用Spring Data JPA完成审计功能
|
3月前
|
Java 数据库连接 API
Spring Boot整合Spring Data JPA进行CRUD和模糊查询
Spring Boot整合Spring Data JPA进行CRUD和模糊查询
38 0
|
3月前
|
存储 NoSQL 安全
go 连接mongodb执行查询的代码
在Go语言中,你可以使用官方的MongoDB驱动程序 `"go.mongodb.org/mongo-driver/mongo"` 来连接MongoDB并执行查询。以下是一个简单的示例代码,演示如何连接MongoDB并执行查询: 首先,确保你已经安装了MongoDB驱动程序: ```bash go get go.mongodb.org/mongo-driver/mongo ``` 然后,可以使用以下示例代码: ```go package main import ( "context" "fmt" "log" "time" "go.mongodb.org/mongo-driv