spring data mongodb之mongodbTemplate查询总结

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: 常用的列表查询(筛选条件,查询字段,排序及分页),相当于关系型数据库的: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
目录
相关文章
|
22天前
|
Java 数据库连接 API
【Java笔记+踩坑】Spring Data JPA
从常用注解、实体类和各层编写方法入手,详细介绍JPA框架在增删改查等方面的基本用法,以及填充用户名日期、分页查询等高级用法。
【Java笔记+踩坑】Spring Data JPA
|
2月前
|
Java Spring 数据库
怎样动动手指就能实现数据操作?Spring Data JPA背后的魔法揭秘
【8月更文挑战第31天】在Java开发中,数据库交互至关重要。传统的JDBC操作繁琐且难维护,而Spring Data JPA作为集成JPA的数据访问层解决方案,提供了CRUD等通用操作接口,显著减少代码量。通过继承`JpaRepository`,开发者能轻松实现数据的增删改查,甚至复杂查询和分页也不再困难。本文将通过示例详细介绍如何利用Spring Data JPA简化数据访问层的开发,提升代码质量和可维护性。
29 0
|
3月前
|
NoSQL Java API
Spring Data MongoDB 使用
Spring Data MongoDB 使用
113 1
|
2月前
|
存储 Java 数据库
|
2月前
|
存储 Java API
|
2月前
|
Java 数据库连接 数据库
Spring Data JPA 与 Hibernate 之区别
【8月更文挑战第21天】
30 0
|
3月前
|
Java 关系型数据库 API
使用Spring Boot和PostgreSQL构建高级查询
使用Spring Boot和PostgreSQL构建高级查询
|
3月前
|
存储 NoSQL Java
使用Spring Boot和MongoDB构建NoSQL应用
使用Spring Boot和MongoDB构建NoSQL应用
|
12月前
|
缓存 Java Go
解决Spring Data JPA查询存在缓存问题及解决方案
解决Spring Data JPA查询存在缓存问题及解决方案
609 0
|
5月前
|
XML Java 数据库连接
Spring Boot的数据访问之Spring Data JPA以及Hibernate的实战(超详细 附源码)
Spring Boot的数据访问之Spring Data JPA以及Hibernate的实战(超详细 附源码)
86 0
下一篇
无影云桌面