Spring Data MongoDB 是的 Spring Data 家族的一部分,可轻松配置并访问 MongoDB。 本文主要介绍在 SpringBoot 中使用 Spring Data MongoDB 操作 MongoDB,使用到的软件版本:Java 1.8.0_191、MongoDB 5.0.5、Spring Boot 2.4.13。

1、引入依赖

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.13</version>
<relativePath />
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>

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

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>

2、配置 MongoDB(application.yml)

在 application.yml 中配置 MongoDB 的相关信息:

spring:
data:
mongodb:
host: 10.49.196.10
port: 27017
database: testdb

3、操作 MongoDB

通过 Spring 提供的 MongoTemplate 来操作 MongoDB。

package com.abc.demo.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongodbCase {
private static Logger logger = LoggerFactory.getLogger(MongodbCase.class);

@Autowired
private MongoTemplate mongoTemplate;

/**
* 创建集合
*/
@Test
public void createCollection() {
mongoTemplate.createCollection("col1");
}

/**
* 获取集合
*/
@Test
public void getCollection() {
MongoCollection<Document> collection = mongoTemplate.getCollection("col1");
logger.info(collection.countDocuments() + "");
}

/**
* 删除集合
*/
@Test
public void dropCollection() {
mongoTemplate.dropCollection("col1");
}

/**
* 插入文档
*/
@Test
public void insetDocumnet() {
MongoCollection<Document> collection = mongoTemplate.getCollection("col1");

List<Document> documents = new ArrayList<>();
Document document1 = new Document("name", "jack").append("age", 20);
Document document2 = new Document("luci", "luci").append("age", 21);
documents.add(document1);
documents.add(document2);
collection.insertMany(documents);
}

/**
* 查询文档
*/
@Test
public void findDocumnet() {
MongoCollection<Document> collection = mongoTemplate.getCollection("col1");

//查询所有
FindIterable<Document> iterable = collection.find();
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
logger.info("1:" + cursor.next().toJson());
}

//order by name limit 2,3 (对应mysql语法,从第二条记录[即跳过第一条]开始,查询三条记录)
iterable = collection.find().sort(new BasicDBObject("name", 1)).skip(1).limit(3);
cursor = iterable.iterator();
while (cursor.hasNext()) {
logger.info("2:" + cursor.next().toJson());
}

//where name='jack'
BasicDBObject query = new BasicDBObject();
query.put("name", "jack");
iterable = collection.find(query);
cursor = iterable.iterator();
while (cursor.hasNext()) {
logger.info("3:" + cursor.next().toJson());
}

//where age in(20,21)
query = new BasicDBObject();
List<Integer> list = new ArrayList<>();
list.add(20);
list.add(21);
query.put("age", new BasicDBObject("$in", list));
iterable = collection.find(query);
cursor = iterable.iterator();
while (cursor.hasNext()) {
logger.info("4:" + cursor.next().toJson());
}

//where age>10 and age<30
query = new BasicDBObject();
query.put("age", new BasicDBObject("$gt", 10).append("$lt", 30));
iterable = collection.find(query);
cursor = iterable.iterator();
while (cursor.hasNext()) {
logger.info("5:" + cursor.next().toJson());
}

//where age!=10
query = new BasicDBObject();
query.put("age", new BasicDBObject("$ne", 10));
iterable = collection.find(query);
cursor = iterable.iterator();
while (cursor.hasNext()) {
logger.info("6:" + cursor.next().toJson());
}

//where name='jack' and age=20
List<BasicDBObject> queryList = new ArrayList<>();
queryList.add(new BasicDBObject("name", "jack"));
queryList.add(new BasicDBObject("age", 20));
query = new BasicDBObject();
query.put("$and", queryList);
iterable = collection.find(query);
cursor = iterable.iterator();
while (cursor.hasNext()) {
logger.info("7:" + cursor.next().toJson());
}
}

/**
* 更新文档
*/
@Test
public void updateDocumnet() {
MongoCollection<Document> collection = mongoTemplate.getCollection("col1");

collection.updateMany(Filters.eq("name", "jack"), new Document("$set",new Document("age", 22)));
}

/**
* 删除文档
*/
@Test
public void deleteDocumnet() {
MongoCollection<Document> collection = mongoTemplate.getCollection("col1");

collection.deleteOne(Filters.eq("name", "jack"));
}
}