MongoDB 查询有四种方式:Query,TextQuery,BasicQuery 和 Bson ,网上太多关于 Query 的查询方式,本文只记录 BasicQuery和Bson 的方式,BasicQuery 相对于 Query 更加的灵活,BasicQuery 就是 Query 的扩展,BasicQuery 可以返回指定列数据。最灵活的是Bson方式。

大写的采坑经验

1.MongoDB 虽然存储很灵活,但是,不要存储Map类型的,不要存储Map类型的,不要存储Map类型的。尽量存储强类型的,尽量存储强类型的,尽量存储强类型的。如果有Map类型的,对于查询指定列的,只能用Bson ,如果是强类型的,就可以直接用Query,TextQuery。

2.复杂类型查询 可以考虑 Bson 方式,Bson 请参考文章最后。

安装Maven包

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

测试数据代码

 for (Long i = 0L; i < 10L; i++) {
MongoDBTestVo vo=new MongoDBTestVo();
vo.setUserId(i);
vo.setEmail("1@1.com");
vo.setName("test"+i.toString());
vo.setPhone(i.toString());
vo.setCreateDate(new Date());
mongoTemplate.insert(vo,"mongodbtest");
}
public class MongoDBTestVo implements Serializable {
private Long userId;
private String email;
private String name;
private String phone;
private Date createDate; public Long getUserId() {
return userId;
} public void setUserId(Long userId) {
this.userId = userId;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}

MongoDBTestVo Code

单条件查询

DBObject obj = new BasicDBObject();
obj.put("userId", new BasicDBObject("$gte", 2)); // userId>=2的条件
//obj.put("userId", 2); userId=2 的条件
Query query = new BasicQuery(obj.toString()); 
List<MongoDBTestVo> result = mongoTemplate.find(query, MongoDBTestVo.class, "mongodbtest");

多条件查询

BasicDBList basicDBList = new BasicDBList();
basicDBList.add(new BasicDBObject("userId", 2L));
basicDBList.add(new BasicDBObject("name","test2")); DBObject obj = new BasicDBObject();
obj.put("$and", basicDBList); Query query = new BasicQuery(obj.toString()); List<MongoDBTestVo> result = mongoTemplate.find(query, MongoDBTestVo.class, "mongodbtest");

查看指定列的数据

DBObject obj = new BasicDBObject();
obj.put("userId", new BasicDBObject("$gte", 2)); BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("userId", 1);
fieldsObject.put("name", 1); Query query = new BasicQuery(obj.toString(), fieldsObject.toString()); List<Map> result = mongoTemplate.find(query, Map.class, "mongodbtest");

BasicQuery查询语句可以指定返回字段,构造函数BasicQuery(DBObject queryObject, DBObject fieldsObject),fieldsObject 这个字段可以指定返回字段

fieldsObject.put(key,value)

key:字段

value:

说明:

1或者true表示返回字段

0或者false表示不返回该字段

_id:默认就是1,没指定返回该字段时,默认会返回,除非设置为0是,就不会返回该字段。

指定返回字段,有时文档字段多并数据大时,我们指定返回我们需要的字段,这样既节省传输数据量,减少了内存消耗,提高了性能,在数据大时,性能很明显的。

Bson查询方式

Bson bson = Filters.and(Arrays.asList(
Filters.gte("createdTime", Calendar.getInstance().getTime()),
Filters.gte("apis.count", 1)));
MongoCursor<Document> cursor = null;
try {
FindIterable<Document> findIterable = mongoTemplate.getCollection("mongodbtest").find(bson);
cursor = findIterable.iterator();
List<MongoDBTestVo> list = new ArrayList<>();
while (cursor.hasNext()) {
Document object = cursor.next();
MongoDBTestVo entity = JSON.parseObject(object.toJson(), MongoDBTestVo.class);
list.add(entity);
}
return list;
} finally {
if (cursor != null) {
cursor.close();
}
}

Bson返回指定列

Bson bson = Filters.and(Arrays.asList(
Filters.gte("createdTime", Calendar.getInstance().getTime()),
Filters.gte("apis.count", 1)));
BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("apis.count", 1);
fieldsObject.put("_id", 0);
MongoCursor<Document> cursor = null;
try {
FindIterable<Document> findIterable = mongoTemplate.getCollection("mongodbtest").find(bson).projection(Document.parse(fieldsObject.toString()));
cursor = findIterable.iterator();
List<MongoDBTestVo> list = new ArrayList<>();
while (cursor.hasNext()) {
Document object = cursor.next();
MongoDBTestVo entity = JSON.parseObject(object.toJson(), MongoDBTestVo.class);
list.add(entity);
}
return list;
} finally {
if (cursor != null) {
cursor.close();
}
}

Bson 排序

Bson bson = Filters.and(Arrays.asList(
Filters.gte("createdTime", Calendar.getInstance().getTime()),
Filters.gte("apis.count", 1)));
BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("apis.count", 1);
fieldsObject.put("_id", 0);
BasicDBObject sort = new BasicDBObject();
sort.put("createdTime", 1);
MongoCursor<Document> cursor = null;
try {
FindIterable<Document> findIterable = mongoTemplate.getCollection("mongodbtest").find(bson).projection(Document.parse(fieldsObject.toString())).sort(sort);
cursor = findIterable.iterator();
List<MongoDBTestVo> list = new ArrayList<>();
while (cursor.hasNext()) {
Document object = cursor.next();
MongoDBTestVo entity = JSON.parseObject(object.toJson(), MongoDBTestVo.class);
list.add(entity);
}
return list;
} finally {
if (cursor != null) {
cursor.close();
}
}

Spring Boot MongoDB 查询操作 (BasicQuery ,BSON)的更多相关文章

  1. Spring Boot中快速操作Mongodb

    Spring Boot中快速操作Mongodb 在Spring Boot中集成Mongodb非常简单,只需要加入Mongodb的Starter包即可,代码如下: <dependency> ...

  2. MongoDB查询操作限制返回字段的方法

    这篇文章主要介绍了MongoDB查询操作限制返回字段的方法,需要的朋友可以参考下   映射(projection )声明用来限制所有查询匹配文档的返回字段.projection以文档的形式列举结果集中 ...

  3. spring boot MongoDB的集成和使用

    前言 上一章节,简单讲解了如何集成Spring-data-jpa.本章节,我们来看看如何集成NoSQL的Mongodb.mongodb是最早热门非关系数据库的之一,使用也比较普遍.最适合来存储一些非结 ...

  4. 使用Spring访问Mongodb的方法大全——Spring Data MongoDB查询指南

    1.概述 Spring Data MongoDB 是Spring框架访问mongodb的神器,借助它可以非常方便的读写mongo库.本文介绍使用Spring Data MongoDB来访问mongod ...

  5. Spring Boot MongoDB JPA 简化开发

    使用SpringBoot提供的@Repository接口,可以完成曾经需要大量代码编写和配置文件定制工作.这些以前让新手程序员头疼,让有经验的程序员引以为傲的配置,由于框架的不断完善,变得不那么重要, ...

  6. Spring Boot学习——数据库操作及事务管理

    本文讲解使用Spring-Data-Jpa操作数据库. JPA定义了一系列对象持久化的标准. 一.在项目中使用Spring-Data-Jpa 1. 配置文件application.properties ...

  7. Spring Boot Mongodb

    Spring注解学习,有助于更好的理解下面代码: @ConditionOnClass表明该@Configuration仅仅在一定条件下才会被加载,这里的条件是Mongo.class位于类路径上 @En ...

  8. spring boot由浅入深(二)spring boot基本命令及操作

    一 spring常见注解 @RestController和@RequestMapping说明: @RestController.这被称为一个构造型(stereotype)注解.它为阅读代码的人们提供建 ...

  9. Spring Boot + MongoDB 使用示例

    本文分别使用 MongoRepository 和 MongoTemplate 实现 MongoDB 的简单的增删改查 本文使用 docker 安装 MongoDB: 使用示例 application. ...

随机推荐

  1. USB安装centos6系统(centos7需要换软件)

    一.下载系统镜像 二.下载安装软碟通软件UltraISO 三.插入U盘制作启动盘 1.用软碟通打开镜像文件:文件-->打开 2.写入映像:启动-->写入硬盘映像 3.等待写入完成 四.系统 ...

  2. DAY13、迭代器,生成器,枚举

    一.迭代器 1.通过迭代器取值的优缺点 优点:不依赖索引取值,完成取值 缺点:不能计算长度,不能指定位取值(只能从前往后逐一取值) 2.可迭代对象 可迭代对象是有—iter—()方法的对象,调用该方法 ...

  3. UVA 10118 Free Candies

    https://vjudge.net/problem/UVA-10118 题目 桌上有4堆糖果,每堆有$N$($N\leqslant 40$)颗.有个熊孩子拿了个可以装5颗糖的篮子,开始玩无聊的装糖游 ...

  4. [BZOJ 2285] [SDOI 2011] 保密

    Description 传送门 Solution 这道题的最大难点在于读懂题意(雾 分数规划求出 \(n\) 到 \(1\cdots n_1\) 每个点的最小 \(\sum\frac{t_i}{s_i ...

  5. logstash/conf.d文件编写

    logstash-01.conf input { beats { port => 5044 host => "0.0.0.0" type => "log ...

  6. 在mobaxterm内连接deb使用lrzsz进行文件传输

    lrzsz随手传文件还是挺方便的. 1.apt install lrzsz 2.rz 3.右键 或者control右键选择 send file useing Z-modem 选择文件上传 接收同理

  7. [SCOI2015]小凸想跑步

    题目描述 小凸晚上喜欢到操场跑步,今天他跑完两圈之后,他玩起了这样一个游戏. 操场是个凸 n 边形, nn 个顶点按照逆时针从 0 ∼n−1 编号.现在小凸随机站在操场中的某个位置,标记为p点.将 p ...

  8. C# 数独算法——LINQ+委托

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sing ...

  9. androidstudio上传代码到git上

    1.首先通过git --bare init 在服务端创建好了一个git仓库:假设git仓库在服务端的地址为:/user/lyh/project/test.git 2.androidstudio上点击V ...

  10. platform驱动分离

    目录 platform驱动分离 框架结构 与输入子系统联系 设备描述 驱动算法 注册机制 程序 测试 platform驱动分离 框架结构 与输入子系统联系 设备描述 驱动算法 注册机制 程序 测试 - ...