在springboot2中使用MongoDB

1、引入依赖

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

2、写入yml文件

spring:
data:
mongodb:
uri: mongodb://user:pwd@localhost:27017/database

注意,下划线部分,根据本机设置,自己调整,如果没有设置权限,去掉黄色部分即可。

还有需要注意的是,涉及到权限时,要不就是使用uri的方式指定路径,要不就使用port、host、username等指定,不可混用。

3、上代码(我觉着定义成静态方法更合适,先不调整了,这个可以用)

@Service
public class MongoUtils { @Autowired
private MongoTemplate mongoTemplate; public void insertOne(String collection, Document document) {
mongoTemplate.getCollection(collection).insertOne(document);
} public void insertMany(String collection, List<Document> documentList) {
mongoTemplate.getCollection(collection).insertMany(documentList);
} public Document findById(String collection, String id) {
Document query = new Document();
query.put("_id", id);
return findOne(collection, query);
} public Document findOne(String collection, Bson filter) {
return findMany(collection, filter).get(0);
} public List<Document> findAll(String collection) {
return findMany(collection, null);
} public List<Document> findMany(String collection, Bson filter) {
filter = handelId(filter);
MongoCollection<Document> mongoCollection = mongoTemplate.getCollection(collection);
FindIterable<Document> findIterable = mongoCollection.find();
MongoCursor<Document> mongoCursor = findIterable.filter(filter).iterator();
List<Document> documentList = new ArrayList<Document>();
while (mongoCursor.hasNext()) {
Document document = mongoCursor.next();
documentList.add(document);
}
return documentList;
} public void updateOne(String collection, Document document) {
Document query = new Document();
query.put("_id", new ObjectId(document.get("_id").toString()));
document.remove("_id");
Document updateDoc = new Document();
updateDoc.put("$set", document);
mongoTemplate.getCollection(collection).updateOne(query, updateDoc);
} private Document handelId(Bson bson) {
if (bson != null) {
Document document = (Document) bson;
Object id = null;
if (document.containsKey("id")) {
id = document.get("id");
document.remove("id");
} else if (document.containsKey("_id")) {
id = document.get("_id");
}
if (id != null) {
ObjectId objId = new ObjectId(id.toString());
document.put("_id", objId);
}
return document;
}
return new Document();
}
}

4、测试类(用法参考)

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Transactional    // 注释后回滚
class MongoDBTest {
@Autowired
private MongoUtils mongoUtils; @BeforeEach
void setUp() {
} @AfterEach
void tearDown() {
} @Test
void insertOne() {
Document doc = new Document();
doc.put("name", "world");
doc.put("age", 16);
mongoUtils.insertOne("collection", doc);
} @Test
void insertMany() {
List<Document> documentList = new ArrayList<Document>();
Document doc = new Document();
doc.put("name", "sam");
doc.put("age", 30);
documentList.add(doc);
doc = new Document();
doc.put("name", "nicole");
doc.put("age", 30);
documentList.add(doc);
mongoUtils.insertMany("collection", documentList);
} @Test
void findById() {
System.out.println(mongoUtils.findById("collection", "5db7a5e66957f95f2a7459a6"));
} @Test
void updateOne() {
Document doc = mongoUtils.findById("collection", "5db7a5e66957f95f2a7459a6");
doc.replace("name", "Jully");
mongoUtils.updateOne("collection", doc);
} @Test
void findOne() {
Document doc = new Document();
doc.put("name", "hello");
System.out.println(mongoUtils.findOne("collection", doc));
} @Test
void findMany() {
Document doc = new Document();
doc.put("id", "5db7a5e66957f95f2a7459a6");
System.out.println(mongoUtils.findMany("collection", doc));
} @Test
void findAll() {
System.out.println(mongoUtils.findAll("collection"));
}
}

如果有问题,欢迎反馈。

springboot2 整合mongodb的更多相关文章

  1. springboot 学习之路 14(整合mongodb的Api操作)

    springboot整合mongodb: mongodb的安装和权限配置  请点击连接参考 mongodb集成 : 第一步:引如pom文件 第二步:配置文件配置mongodb路径: 第三步:关于mon ...

  2. spring MVC 整合mongodb

    Spring Mongodb 目录 1 SPRING整合MONGODB 1 1.1 环境准备 1 1.2 包依赖 1 1.3 配置 2 2 案列 5 2.1 SPRING MVC整合MONGODB代码 ...

  3. MongoDB系列:四、spring整合mongodb,带用户验证

    在前面的两篇博客 MongoDB常用操作练习.springboot整合mongoDB的简单demo中,我们基本上熟悉了mongodb,也把它与spring boot进行了整合并且简单使用.在本篇博客中 ...

  4. java操作mongodb & springboot整合mongodb

    简单的研究原生API操作MongoDB以及封装的工具类操作,最后也会研究整合spring之后作为dao层的完整的操作. 1.原生的API操作 pom.xml <!-- https://mvnre ...

  5. SpringBoot整合mongoDB

    MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的. 这一片文章介绍一个springboot整合mongodb,如果你了解整合mysql之类的 ...

  6. SpringMVC整合Mongodb开发,高级操作

    开发环境: 操作系统:windows xpMongodb:2.0.6依 赖 包:Spring3.2.2 + spring-data-mongodb-1.3.0 + Spring-data-1.5 +  ...

  7. spring整合mongodb

    使用spring整合mongodb maven 依赖 <dependency> <groupId>org.mongodb</groupId> <artifac ...

  8. SpringBoot非官方教程 | 第八篇:springboot整合mongodb

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot8-mongodb/ 本文出自方志朋的博客 这篇文 ...

  9. SpringMVC整合MongoDB

    首先,在pom文件中新增spring-data-mongodb的依赖: <dependency> <groupId>org.springframework.data</g ...

随机推荐

  1. Java Integer类的缓存

    首先看一段代码(使用JDK 5),如下: public class Hello { public static void main(String[] args) { int a = 1000, b = ...

  2. 如何用for..of.. 遍历一个普通的对象?

    如何用for..of.. 遍历一个普通的对象? 首先了解一下for..of..: 它是es6新增的一个遍历方法,但只限于迭代器(iterator), 所以普通的对象用for..of遍历 是会报错的.下 ...

  3. windows命令行下redis读取中文字符乱码

    我在eclipse上对redis进行了一个操作,添加了一个中文字符串进去,可以看到是添加成功了的 但是在命令行中读取的时候却成了乱码,如下图所示 这是因为windows命令行的编码是gbk 可以通过如 ...

  4. linux初始化中的错误处理

    你必须记住一件事, 在注册内核设施时, 注册可能失败. 即便最简单的动作常常需要内存 分配, 分配的内存可能不可用. 因此模块代码必须一直检查返回值, 并且确认要求的操作 实际上已经成功. 如果在你注 ...

  5. 【js】vue 2.5.1 源码学习 (九) 响应数组对象的变

    大体思路(八) 本节内容: 1.Observe 如何响应数组的变化 代理原型 数组变异方法 shell cacheArrProto methods 新添加的数组需要加到显示系统里面,拦截 push等的 ...

  6. 中和IOS七层架构和TCP/IP四层架构的五层架构

    五层架构分别为应用层.运输层.网络层.数据链路层.物理层. IOS架构把应用层又细分为应用层.表示层.会话层 TCP/IP把网络层改名网际层,数据链路层和物理层结合成网络接口层 其实只要学习五层协议, ...

  7. 【21.58%】【codeforces 746D】Green and Black Tea

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  8. 2019-2-27-win10-uwp-去掉-Flyout-边框

    title author date CreateTime categories win10 uwp 去掉 Flyout 边框 lindexi 2019-02-27 17:48:46 +0800 201 ...

  9. 关于react打包之后静态资源加载错误的问题

    之前在打包react项目时发现一些问题,打包出来后我的一部分png图标加载不出来,开发者模式发现他们的路径中莫名其妙混入了我在react-router路由中使用<Browserrouter> ...

  10. IntPtr、Struct 相互转换

    一般写c#代码基本用不到 相互转换 只有调用c++中的dll动态库的时候才用的到 struct转intptr public static IntPtr StructToIntPtr<T>( ...