文章目录
1、搭建demo工程
2、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- Generated by https://start.springboot.io -->
<!-- 优质的 spring/boot/data/security/cloud 框架中文文档尽在 => https://springdoc.cn -->
<groupId>com.atguigu</groupId>
<artifactId>mongo-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mongo-demo</name>
<description>mongo-demo</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3、application.properties配置内容如下:
spring.application.name=mongo-demo
spring.data.mongodb.uri=mongodb://192.168.74.148:27017/atguigu
4、编写实体类 User
package com.atguigu.mongo.demo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "user")
@Data
public class User {
@Id
private Long id;
private String name;
private Integer age;
private Boolean gender;
}
5、新增一条文档
package com.atguigu.mongo.demo;
import com.atguigu.mongo.demo.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
@SpringBootTest
class MongoDemoApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
@Test
void contextLoads() {
this.mongoTemplate.insert(new User(1L, "张三", 18, false));
}
}
atguigu> use atguigu
already on db atguigu
atguigu> db.user.find()
[
{
_id: Long("1"),
name: '张三',
age: 18,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
}
]
atguigu>
6、新增多条文档
package com.atguigu.mongo.demo;
import com.atguigu.mongo.demo.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.util.Arrays;
@SpringBootTest
class MongoDemoApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
@Test
void contextLoads() {
//this.mongoTemplate.insert(new User(1L, "张三", 18, false));
this.mongoTemplate.insert(Arrays.asList(
new User(2L, "李四", 19, true),
new User(3L, "王五", 20, true),
new User(4L, "赵六", 21, false),
new User(5L, "田七", 22, false)
), User.class);
}
}
test> use atguigu
switched to db atguigu
atguigu> db.user.find()
[
{
_id: Long("1"),
name: '张三',
age: 18,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("2"),
name: '李四',
age: 19,
gender: true,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("3"),
name: '王五',
age: 20,
gender: true,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("4"),
name: '赵六',
age: 21,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("5"),
name: '田七',
age: 22,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
}
]
atguigu>
7、保存或更新一个文档
- .save(…):MongoTemplate类中的一个方法,用于保存或更新一个文档到MongoDB数据库中。如果数据库中已经存在具有相同唯一标识符(比如这里的_id字段)的文档,则更新该文档;如果不存在,则插入新文档。
package com.atguigu.mongo.demo;
import com.atguigu.mongo.demo.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.util.Arrays;
@SpringBootTest
class MongoDemoApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
@Test
void contextLoads() {
//this.mongoTemplate.insert(new User(1L, "张三", 18, false));
this.mongoTemplate.insert(Arrays.asList(
new User(2L, "李四", 19, true),
new User(3L, "王五", 20, true),
new User(4L, "赵六", 21, false),
new User(5L, "田七", 22, false)
), User.class);
}
@Test
void testSave() {
this.mongoTemplate.save(new User(1L, "张三", 21, false));
this.mongoTemplate.save(new User(6L, "孙八", 23, false));
}
}
atguigu> db.user.find()
[
{
_id: Long("1"),
name: '张三',
age: 21,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("2"),
name: '李四',
age: 19,
gender: true,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("3"),
name: '王五',
age: 20,
gender: true,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("4"),
name: '赵六',
age: 21,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("5"),
name: '田七',
age: 22,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("6"),
name: '孙八',
age: 23,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
}
]
atguigu>
8、通过id查询
@Test
void testFind() {
System.out.println(this.mongoTemplate.findById(1L, User.class));
}
User(id=1, name=张三, age=21, gender=false)
atguigu> db.user.find({_id:1})
[
{
_id: Long("1"),
name: '张三',
age: 21,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
}
]
9、查询年龄为21的用户
@Test
void testFind() {
this.mongoTemplate.find(Query.query(Criteria.where("age").is(21)), User.class).forEach(System.out::println);
}
User(id=1, name=张三, age=21, gender=false)
User(id=4, name=赵六, age=21, gender=false)
atguigu> db.user.find({age:21})
[
{
_id: Long("1"),
name: '张三',
age: 21,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("4"),
name: '赵六',
age: 21,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
}
]
10、查询年龄大于21的用户
@Test
void testFind() {
this.mongoTemplate.find(Query.query(Criteria.where("age").gt(21)), User.class).forEach(System.out::println);
}
User(id=5, name=田七, age=22, gender=false)
User(id=6, name=孙八, age=23, gender=false)
atguigu> db.user.find({age:{$gt:21}})
[
{
_id: Long("5"),
name: '田七',
age: 22,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
},
{
_id: Long("6"),
name: '孙八',
age: 23,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
}
]
11、查询年龄大于21且姓名包含孙的用户
void testFind() {
this.mongoTemplate.find(Query.query(Criteria
.where("age").gt(21)
.and("name").regex("孙")
), User.class).forEach(System.out::println);
}
User(id=6, name=孙八, age=23, gender=false)
atguigu> db.user.find({age:{$gt:21},name:{$regex:'孙'}})
[
{
_id: Long("6"),
name: '孙八',
age: 23,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
}
]
12、查询年龄大于21且姓名包含孙并且按年龄降序排列
先添加一个用户 孙小小
@Test
void testFind() {
this.mongoTemplate.find(Query.query(Criteria
.where("age").gt(21)
.and("name").regex("孙")
).with(Sort.by(Sort.Order.desc("age")))
, User.class).forEach(System.out::println);
}
User(id=7, name=孙小小, age=24, gender=true)
User(id=6, name=孙八, age=23, gender=false)
atguigu> db.user.find({age:{$gt:21},name:{$regex:'孙'}}).sort({age:-1})
[
{
_id: Long("7"),
_class: 'com.atguigu.mongo.demo.pojo.User',
age: 24,
gender: true,
name: '孙小小'
},
{
_id: Long("6"),
name: '孙八',
age: 23,
gender: false,
_class: 'com.atguigu.mongo.demo.pojo.User'
}
]
13、查询年龄大于21且姓名包含孙并且按年龄降序排列且跳过前两个
@Test
void testFind() {
this.mongoTemplate.find(Query.query(Criteria
.where("age").gt(21)
.and("name").regex("孙")
).with(Sort.by(Sort.Order.desc("age"))).skip(2).limit(2)
, User.class).forEach(System.out::println);
}
@Test
void testFind() {
this.mongoTemplate.find(Query.query(Criteria
.where("age").gt(21)
.and("name").regex("孙")
).with(Sort.by(Sort.Order.desc("age"))).with(PageRequest.of(1,2))
, User.class).forEach(System.out::println);
}
因为满足条件的一共就两个,所以跳过前两个,就没有数据喽
atguigu> db.user.find({age:{$gt:21},name:{$regex:'孙'}}).sort({age:-1}).limit(2).skip(2)
atguigu>
14、把年龄为22的用户修改为28岁
@Test
void testUpdate() {
UpdateResult result = this.mongoTemplate.updateFirst(
Query.query(Criteria.where("age").is(22)),
Update.update("age", 28),
User.class);
System.out.println("result.getMatchedCount() = " + result.getMatchedCount());
System.out.println("result.getModifiedCount() = " + result.getModifiedCount());
}
result.getMatchedCount() = 1
result.getModifiedCount() = 1
15、删除年龄为24的用户
@Test
void testDelete() {
DeleteResult age = this.mongoTemplate.remove(Query.query(Criteria.where("age").is(24)), User.class);
System.out.println("age.getDeletedCount() = " + age.getDeletedCount());
}
age.getDeletedCount() = 1