1.创建一个SpringBoot工程
创建工程步骤省略,直接进入正题不玩虚的......................采用MongoDB首先要导入架包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
这是第一步也是后面围着这一个架包进行操作API最关键的一步
2.配置application.yml
spring:
application:
name: spring-boot-mongdb
data:
mongodb:
uri: mongodb://127.0.0.1:27017/test
spring: application: name: spring-boot-mongdb //工程名称 data: mongodb: uri: mongodb://127.0.0.1:27017/test //连接mongodb的路径
127.0.0.1为本地路径,我是安装在本地进行操作,如有MongoDB安装在服务器以及虚拟机的话,填写服务器以及虚拟机地址即可...........................
/test为当前MongoDB的数据库..................这个很好理解,类似Mysql数据库的库一样......................废话不多说上代码
3.建立一个表
@Document(collection = "demo_collection")
@Data
public class DemoEntity implements Serializable {
@Id
private Long id;
private String description;
private String by;
private String url;
}
解说: @Document(collection = "demo_collection") 为表
下面的如 ID / description为表里面的属性
4.操作API进行(增/删/改/查)
@SpringBootTest
class MongdbApplicationTests {
@Autowired
private MongoTemplate mongoTemplate;
/*
Mongodb 数据添加
*/
@Test
void save() {
for (int i = 0;i<=100;i++){
DemoEntity entity = new DemoEntity();
entity.setId(1L+i);
entity.setDescription("aaaa"+i);
entity.setBy("by"+i);
entity.setUrl("http://www.baidu.com"+i);
mongoTemplate.save(entity);
}
}
/*
Mongodb 数据删除
*/
@Test
void delete(){
DemoEntity entity = new DemoEntity();
entity.setId(1111L);
mongoTemplate.remove(entity);
}
/*
Mongodb 数据修改
*/
@Test
void update(){
DemoEntity entity = new DemoEntity();
entity.setId(1L);
entity.setBy("bybybybybybyby");
entity.setDescription("aaaaaaaaaaaaaaaaa");
entity.setUrl("1232132132131231231");
mongoTemplate.save(entity);
}
/*
Mongodb 数据查询
*/
@Test
void select(){
List<DemoEntity> list = new ArrayList<>();
list = mongoTemplate.findAll(DemoEntity.class,"demo_collection");
System.out.println(list);
}
/*
Mongodb 根据查询条件进行排序
*/
@Test
void selectByCond(){
String dataName = "aaaa83";
ConditionalOperators.Cond condOperation = ConditionalOperators.when(Criteria.where("description").is(dataName))
.thenValueOf("1")
.otherwise("0");
//返回的字段
ProjectionOperation project = Aggregation.project("id","description","by",
"url");
Aggregation aggregation = Aggregation.newAggregation(
project.and(condOperation).as("sortNo"),
Aggregation.sort(Sort.by(Sort.Order.asc("sortNo"))));
List<DemoEntity> results = mongoTemplate.aggregate(aggregation, DemoEntity.class, DemoEntity.class).getMappedResults();
for (int i = 0;i<results.size();i++){
System.out.println(results.get(i));
}
}
}
mongoTemplate是上面我导入的JAR包后产生的一个类,然后把这个类注入到Spring中进行管理,然后进行调用增/删改查