java单机
连接mongodb
/**
* 无需密码连接MongoDb
*/
public static void getMongoNoPass() {
// 连接到 mongodb 服务
com.mongodb.MongoClient mongoClient = new com.mongodb.MongoClient("127.0.0.1", 27017);
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("javaTest");
System.out.println("Connect to database successfully");
}
/**
* 需要账户密码连接MongoDb
*/
public static MongoDatabase getMongo() {
try {
//数据库链接选项
MongoClientOptions mongoClientOptions = MongoClientOptions.builder().build();
//数据库链接方式
/** MongoDB 3.0及其以上版本使用该方法 */
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("admin", "admin", "admin".toCharArray());
//数据库链接地址
ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
//获取数据库链接client
com.mongodb.MongoClient client = new com.mongodb.MongoClient(serverAddress, mongoCredential, mongoClientOptions);
MongoDatabase mongoDatabase = client.getDatabase("javaTest");
System.out.println("Connect to database successfully");
return mongoDatabase;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
操作集合
public static void collection(MongoDatabase mongoDatabase) {
mongoDatabase.createCollection("test");
System.out.println("集合创建成功");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
System.out.println("集合 test 选择成功:");
mongoDatabase.getCollection("test").drop();
System.out.println("删除test集合成功");
}
操作文档
public static void document(MongoDatabase mongoDatabase) {
MongoCollection<Document> collection = mongoDatabase.getCollection("test1");
Document document = new Document("title", "MongoDB").append("description", "database").
append("likes", 100);
Document document1 = new Document("title", "MongoDB1").append("description", "database1").
append("likes", 110);
List<Document> documents = new ArrayList<Document>();
documents.add(document);
documents.add(document1);
collection.insertMany(documents);
System.out.println("插入两个文档");
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println("检索的文档:" + mongoCursor.next());
}
System.out.println("更新文档 将文档中likes=100的文档修改为likes=200");
collection.updateMany(Filters.eq("likes", 100), new Document("$set", new Document("likes", 200)));
//检索查看结果
FindIterable<Document> findIterable1 = collection.find();
MongoCursor<Document> mongoCursor1 = findIterable1.iterator();
while (mongoCursor1.hasNext()) {
System.out.println("检索的文档1:" + mongoCursor1.next());
}
//删除符合条件的第一个文档
collection.deleteOne(Filters.eq("likes", 200));
//删除所有符合条件的文档
// collection.deleteMany (Filters.eq("likes", 200));
}
整合SpringBoot
DEMO前置条件
引入一类
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
增加配置
spring:
data:
mongodb:
host: 127.0.0.1
port: 27017
username: admin
password: admin
database: javaTest
entity
@Data
//指定要对应的文档名(集合名称 如未创建,在第一次插入数据的时候自动创建)
@Document(collection = "student")
public class Student {
public Student() {
}
/*** 自定义mongo主键 加此注解可自定义主键类型以及自定义自增规则
* 若不加 插入数据数会默认生成 ObjectId 类型的_id 字段
* org.springframework.data.annotation.Id 包下
* mongo库主键字段还是为_id 。不必细究(本文实体类中为id)
*/
@Id
private Integer id;
private String username;
private LocalDateTime timer = LocalDateTime.now();
}
config
/**
* 监听芒果 保存数据
* 此类若不加,那么插入的一行会默认添加一个_class字段来存储实体类类型 如(com.example.demo.entity.Student)
*/
@Configuration
public class ApplicationReadyListener implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
MongoTemplate oneMongoTemplate;
private static final String TYPEKEY = "_class";
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
MongoConverter converter = oneMongoTemplate.getConverter();
if (converter.getTypeMapper().isTypeKey(TYPEKEY)) {
((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
}
}
}
使用MongoTemplate
@Autowired
private MongoTemplate mongoTemplate;
@GetMapping("createCollection")
public String createCollection() {
Student student = new Student();
student.setUsername("test1");
student.setId(1);
mongoTemplate.insert(student);
logger.info("插入一条数据成功:{}", JSON.toJSONString(student));
return "";
}
@GetMapping("updateCollection")
public String updateCollection() {
Query query = new Query(Criteria.where("_id").is(1));
Update update = new Update().set("username", "UpdateTest1");
mongoTemplate.updateFirst(query, update, Student.class);
logger.info("更新一条数据");
return "";
}
@GetMapping("removeCollection")
public String removeCollection() {
Query query1 = new Query(Criteria.where("_id").is(1));
mongoTemplate.remove(query1, Student.class);
logger.info("删除一条数据");
return "";
}
@GetMapping("createCollectionAll")
public String createCollectionAll() {
List<Student> list = new ArrayList<Student>(10);
for (int i = 2; i < 12; i++) {
Student student = new Student();
student.setUsername("bootTest" + i);
student.setId(i);
list.add(student);
}
mongoTemplate.insertAll(list);
logger.info("插入N条数据成功:{}", JSON.toJSONString(list));
return "";
}
@GetMapping("getCollection")
public String getCollection() {
//精确查询
Query query = new Query(Criteria.where("_id").is(2));
Student one = mongoTemplate.findOne(query, Student.class);
logger.info("精确查询:{}", JSON.toJSONString(one));
//模糊查询
Pattern pattern = Pattern.compile("^.*bootTest.*$", Pattern.CASE_INSENSITIVE);
Query query1 = new Query(Criteria.where("username").regex(pattern));
List<Student> studentList = mongoTemplate.find(query1, Student.class);
logger.info("模糊匹配:{}", JSON.toJSONString(studentList));
//倒序查询
Query query2 = new Query().with(Sort.by(Sort.Direction.DESC,"id"));
List<Student> students = mongoTemplate.find(query2, Student.class);
logger.info("ID倒序查询:{}", JSON.toJSONString(students));
Query query3 = new Query();
query3.with(Sort.by(Sort.Direction.DESC,"id"));
//skip 和java8 Stream 中用法一致,即跳过2条数据, limit为分页的每页最大条数3则每页分3条
query3.skip(2).limit(3);
List<Student> students1 = mongoTemplate.find(query3, Student.class);
logger.info("分页查询:{}", JSON.toJSONString(students1));
return "";
}
使用MongoRepository
@Repository
public interface StudentRepository extends MongoRepository<Student, Integer> {
}
因为引入的 MongoRepository 是一种 JPA 框架,所以增删改查可以参考 Spring Data JPA 方法命名规范,举几个例子
方法关键字 | 示例 | 等价于SQL |
---|---|---|
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is,Equals | findByFirstname,findByFirstnameIs,findByFirstnameEquals | … where x.firstname = ?1 |
@Autowired
private StudentRepository studentRepository;
@GetMapping("createCollection/MongoRepository")
public void saveStudentMongoRepository() {
Student student = new Student();
student.setUsername("studentRepository");
student.setId(101);
studentRepository.save(student);
logger.info("使用MongoRepository增加数据:{}", JSON.toJSONString(student));
}
/**
* 测试批量新增列表
*/
@GetMapping("createCollectionAll/MongoRepository")
public void testSaveList() {
List<Student> list = new ArrayList<Student>(10);
for (int i = 0; i < 10; i++) {
Student student = new Student();
student.setUsername("bootTest1000" + i);
student.setId(1000+i);
list.add(student);
}
studentRepository.saveAll(list);
logger.info("使用MongoRepository批量增加数据:{}", JSON.toJSONString(list));
}
/**
* 测试更新
*/
@GetMapping("collectionDel/MongoRepository")
public void testUpdate() {
studentRepository.findById(1000).ifPresent(student -> {
student.setUsername("MongoRepository更新之后的名称");
studentRepository.save(student);
logger.info("使用MongoRepository更新数据:{}", JSON.toJSONString(student));
});
//根据主键删除
//studentRepository.deleteById(10000);
//全部删除
//studentRepository.deleteAll();
}
@GetMapping("getCollection/MongoRepository")
public void testQuery() {
/**
* 排序规则
*/
Sort sort = Sort.by("id").descending();
/**
* 分页
*/
PageRequest pageRequest = PageRequest.of(0, 3, sort);
/**
* 分页查询
*/
Page<Student> articleRepoAll = studentRepository.findAll( pageRequest);
logger.info("【总页数】= {}", articleRepoAll.getTotalPages());
logger.info("【总条数】= {}", articleRepoAll.getTotalElements());
logger.info("【当前页数据】= {}", JSON.toJSONString( articleRepoAll.getContent()));
}