@SpringBootTest
@Slf4j
public class MyMongo {
@Autowired
private MongoTemplate mongoTemplate;
@Test
void createCollection() {
boolean emp = mongoTemplate.collectionExists("emp");
if (emp) {
mongoTemplate.dropCollection("emp");
}
mongoTemplate.createCollection("emp");
}
@Test
void testInsert() {
Employee employee = new Employee(1, "aa", 2223, 333.00, new Date());
//mongoTemplate.insert(employee); id存在会报错
//save在id不存在时是insert,存在则是update
mongoTemplate.save(employee);
List<Employee> employees = Arrays.asList(
new Employee(2, "bb", 45, 234.00, new Date()),
new Employee(3, "cc", 46, 224.00, new Date()),
new Employee(4, "dd", 47, 284.00, new Date())
);
//mongoTemplate.save(employees); save不支持批量插入
mongoTemplate.insert(employees, Employee.class);
}
@Test
void testFind1() {
System.out.println("========查询所有===========");
List<Employee> list = mongoTemplate.findAll(Employee.class);
list.forEach(System.out::println);
System.out.println("========根据id查询==========");
Employee employee = mongoTemplate.findById(1, Employee.class);
System.out.println(employee);
System.out.println("========查询第一个==========");
Employee one = mongoTemplate.findOne(new Query(), Employee.class);
System.out.println(one);
}
@Test
void testFind2() {
Query query = new Query(new Criteria()
//age>=40 && salary>234
.andOperator(
Criteria.where("age").gte(40),
Criteria.where("salary").gt(234)
)
//name like "%a%" or name like "%b%"
.orOperator(
Criteria.where("name").regex("a"),
Criteria.where("name").regex("b")
)
);
//order by name desc, id asc
//limit 0, 4;
query.with(
Sort.by(
Sort.Order.desc("name"),
Sort.Order.asc("id")
)
).skip(0).limit(4);
List<Employee> employees = mongoTemplate.find(query, Employee.class);
employees.forEach(System.out::println);
}
@Test
void testUpdate() {
Query query = new Query(Criteria.where("salary").gt(200));
Update update = new Update()
.set("salary", "1111")
.set("name", "章换行");
//只更新第一条
mongoTemplate.updateFirst(query, update, Employee.class);
//更新全部
mongoTemplate.updateMulti(query, update, Employee.class);
//不存在则插入
update.setOnInsert("age", "0922");
UpdateResult upsert = mongoTemplate.upsert(query, update, Employee.class);
//修改的记录数
long modifiedCount = upsert.getModifiedCount();
}
@Test
void testDelete() {
//删除所有,不如mongoTemplate.dropCollection();
//mongoTemplate.remove(new Query(), Employee.class);
Query query = new Query(Criteria.where("salary").gt(20000));
mongoTemplate.remove(query, Employee.class);
}
}
05-18
474
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)