MongoDB 应用实战
最新驱动的地址
https://mongodb.github.io/mongo-java-driver/4.1/driver/
1. java 原生客户端
引入maven
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.1.1</version>
</dependency>
</dependencies>
public class QuickStart {
public static void main(String[] args) {
// 连接本地默认端口的Mongod
// MongoClient mongoClient = MongoClients.create()
// 连接远程服务的指定端口的Mongod
// MongoClient mongoClient = MongoClients.create("mongodb://host1:27017");
// 连接指定端口复制集
// MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet");
// 连接 mongos路由: 连接一个
// MongoClient mongoClient = MongoClients.create( "mongodb://localhost:27017" );
// 连接多个mongos路由
MongoClient mongoClient = MongoClients.create("mongodb://111.229.189.98:4000");
//获取数据库
MongoDatabase database = mongoClient.getDatabase("productdb");
// 获取集合
MongoCollection<Document> productdesc=database.getCollection( "productdesc" );
Document doc = new Document("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
.append("info", new Document("x", 203).append("y", 102));
productdesc.insertOne(doc);
Bson eq = eq("name", "MongoDB");
FindIterable<Document> find = productdesc.find(eq);
Document first=find.first();
System.out.println(first);
}
}
Spring Boot 整合:
https://docs.spring.io/spring-data/mongodb/docs/3.1.2/reference/html/#preface
1. 引入maven ```java <?xml version=”1.0” encoding=”UTF-8”?>4.0.0 org.springframework.boot spring-boot-starter-parent 2.4.0 com.example demo 0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-data-mongodb org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.projectlombok lombok 1.18.12
2. 添加配置类<br />a.yml中配置:
```java
无密码:test为库名
spring.data.mongodb.uri=mongodb://localhost:27017/test
spring:
data:
mongodb:
uri: mongodb://localhost:27017/test
有密码:root,123456,test为库名
spring:
data:
mongodb:
uri: mongodb://root:123456@localhost:27017/test
b.代码中配置:
package com.example.demo.config;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
@Configuration
public class AppConfig {
public @Bean
MongoClient mongoClient() {
return MongoClients.create("mongodb://111.229.189.98:4000");
}
public @Bean
MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "productdb");
}
}
- 测试类 ```java package com.example.demo;
public class Person {
private String id; private String name; private int age;
public Person(String name, int age) { this.name = name; this.age = age; }
public String getId() { return id; } public String getName() { return name; } public int getAge() { return age; }
@Override public String toString() { return “Person [id=” + id + “, name=” + name + “, age=” + age + “]”; }
}
package com.example.demo;
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component;
import java.util.List;
import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Query.query; import static org.springframework.data.mongodb.core.query.Update.update;
@Component @Slf4j public class ApplicationRunnerTest implements ApplicationRunner{
@Autowired
private MongoTemplate mongoOps;
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
Person p = new Person("Joe", 34);
// 插入文档
mongoOps.insert(p);
log.info("Insert: " + p);
// 查询文档
p = mongoOps.findById(p.getId(), Person.class);
log.info("Found: " + p);
// 更新文档
mongoOps.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
p = mongoOps.findOne(query(where("name").is("Joe")), Person.class);
log.info("Updated: " + p);
// 删除文档
mongoOps.remove(p);
// Check that deletion worked
List<Person> people = mongoOps.findAll(Person.class);
log.info("Number of people = : " + people.size());
mongoOps.dropCollection(Person.class);
}
} ```