1.依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.代码例子
package com.sugon.cloud.utils;
import com.mongodb.client.*;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class MongoDBJDBC {
public static void main(String args[]) throws Exception {
//通过连接认证获取MongoDB连接
MongoClient mongoClient = MongoClients.create("mongodb://admin:123456@10.0.42.211:27017/?authSource=admin");
//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("db01");
MongoDBJDBC.addDocument(mongoDatabase.getCollection("student"));
mongoClient.close();
}
private static void addDocument(MongoCollection<Document> collection){
List<Document> documents = new ArrayList<Document>();
for (int i = 0; i < 100; i++) {
Document document = new Document("姓名", "liuyunshengsir"+i).
append("学号", "1101"+i).
append("学院", "计算机科学与技术学院").
append("专业", "软件工程").
append("班级", "11-01班").
append("成绩", i);
documents.add(document);
}
collection.insertMany(documents);
}
}
3.参考
更多参考官方文档