项目地址:https://gitee.com/xiiiao/mongo-learning
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.1.RELEASEversion>
<relativePath/>
parent>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-mongodbartifactId>
dependency>
此依赖基于mongodb-driver 4.0.4,spring-data-mongo-3.0.1,如果需要自行查看相关官方文档,请确定文档版本一致。
可以通过spring的工厂类MongoClientFactoryBean
或者mongo提供的工具类MongoClients
来创建客户端实例
public @Bean
MongoClientFactoryBean mongo() {
MongoClientFactoryBean mongo = new MongoClientFactoryBean();
MongoCredential credential=MongoCredential.createCredential(mongoSettings.getUsername(),mongoSettings.getDb(),mongoSettings.getPass().toCharArray());
//can not add credential in this way
MongoClientSettings setting=MongoClientSettings.builder()
.credential(credential)
.build();
// mongo.setMongoClientSettings(setting);
mongo.setHost(mongoSettings.getIpAddress());
mongo.setPort(mongoSettings.getPort());
mongo.setCredential(new MongoCredential[]{credential});
return mongo;
}
需要注意的是,通过MongoClientFactoryBean
来创建实例,mongo认证信息需要通过setCredential
方法来设置,setMongoClientSettings
方法设置不会生效。
@Bean
public MongoClient rawClient(){
MongoCredential credential=MongoCredential.createCredential(mongoSettings.getUsername(),mongoSettings.getDb(),mongoSettings.getPass().toCharArray());
// ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017");
MongoClientSettings setting=MongoClientSettings.builder()
.credential(credential)
// .applyConnectionString(connectionString)
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(new ServerAddress(mongoSettings.getIpAddress(), mongoSettings.getPort())))
.mode(ClusterConnectionMode.SINGLE)
.requiredClusterType(ClusterType.STANDALONE)
).build();
return MongoClients.create(setting);
}
两种方式任选其一即可,完成后就可以通过@Autowired
注解在项目中引入MongoClient
进行相关操作。
在完成初始化之后,可以编写单元测试来简单验证客户端的功能。
先通过mongoShell插入数据
db.foo.insert(
[
{ _id: 1, name: "Java Hut", description: "Coffee and cakes" },
{ _id: 2, name: "Burger Buns", description: "Gourmet hamburgers" },
{ _id: 3, name: "Coffee Shop", description: "Just coffee" },
{ _id: 4, name: "Clothes Clothes Clothes", description: "Discount clothing" },
{ _id: 5, name: "Java Shopping", description: "Indonesian goods" }
]
)
然后编写如下单元测试
@Autowired
MongoClient client;
Consumer<Document> printConsumer = new Consumer<Document>() {
@Override
public void accept(final Document document) {
log.info(document.toJson());
}
};
@Test
void testRawCollections() {
MongoCollection<Document> collection=client.getDatabase("test").getCollection("foo");
log.info(collection.countDocuments());
FindIterable<Document> iterabl=collection.find();
iterabl.forEach(printConsumer);
}
一些顺利的话,可以在控制台看到如下日志
2020-08-11 15:47:10.773 INFO 13604 --- [ main] mongo.ClientTest : 5
2020-08-11 15:47:10.970 INFO 13604 --- [ main] mongo.ClientTest : {"_id": 1.0, "name": "Java Hut", "description": "Coffee and cakes"}
2020-08-11 15:47:10.970 INFO 13604 --- [ main] mongo.ClientTest : {"_id": 2.0, "name": "Burger Buns", "description": "Gourmet hamburgers"}
2020-08-11 15:47:10.970 INFO 13604 --- [ main] mongo.ClientTest : {"_id": 3.0, "name": "Coffee Shop", "description": "Just coffee"}
2020-08-11 15:47:10.971 INFO 13604 --- [ main] mongo.ClientTest : {"_id": 4.0, "name": "Clothes Clothes Clothes", "description": "Discount clothing"}
2020-08-11 15:47:10.971 INFO 13604 --- [ main] mongo.ClientTest : {"_id": 5.0, "name": "Java Shopping", "description": "Indonesian goods"}
除mongo原生客户端MongoClient
外,sping还提供了mongoTemplate
工具类,后续介绍都会通过这两个类进行,并提供相关对比
在学习mongo时,一个好用的客户端工具也很重要,这里参考了别人使用的NoSqlBooster,有免费版,大家可以自行去官网下载。
另外在通过原生的objectId进行查询时,需要通过如下方式,不然什么都查不到,这里被卡了好几次,经常会忘
db.topicOption.find({"_id":ObjectId("5f8d88495f11166b5542e06f")})