maven构建springboot项目
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<version>2.2.4.RELEASEversion>
dependency>
<dependency>
<groupId>org.mongodbgroupId>
<artifactId>mongo-java-driverartifactId>
<version>3.4.3version>
dependency>
dependencies>
/** * 连接本地数据库 */
@Test
public void testConnection(){
//创建mongodb客户端
MongoClient mongoClient = new MongoClient("localhost", 27017);
System.out.println(mongoClient);
}
连接字符串uri必须写数据库db, 反之抛异常 MongoSecurityException
/** * 采用连接字符串 */
@Test
public void testConnection2(){
MongoClientURI mongoClientURI = new MongoClientURI("mongodb://root:root@localhost:27017/demo");
MongoClient mongoClient = new MongoClient(mongoClientURI);
System.out.println(mongoClient);
}
mongodb://username:password@host:prot /database ?options
mongodb:固定前缀
username:账号,可不填
password:密码,可不填
host:主机名或ip地址,只有host主机名为必填项。
port:端口可不填,默认27017
/database:连接某个数据库
?options:连接参数,key/value对
//连接本地数据库27017端口
mongodb://localhost
//使用用户名root密码为1234连接本地数据库27017端口
mongodb://root:1234@localhost
//连接三台主从服务器,端口为27017、27018、27019
mongodb://localhost,localhost:27018,localhost:27019
@Test
public void testFind(){
//连接客户端
MongoClientURI mongoClientURI = new MongoClientURI("mongodb://root:1234@localhost:27017/demo");
MongoClient mongoClient = new MongoClient(mongoClientURI);
//连接数据库
MongoDatabase database = mongoClient.getDatabase("demo");
//连接collection集合
MongoCollection<Document> collection = database.getCollection("student");
//查询第一个文档
Document myDoc = collection.find().first();
//得到文档内容json串
String json = myDoc.toJson();
System.out.println(json);
}
//创建集合
database.createCollection("teacher");
//插入文档
Document document = new Document();
document.append("name","xihe老师");
document.append("age",18);
document.append("marry","new..");
collection.insertOne(document);
}
collection.insertMany(documentList);
//查询所有
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()){
Document document = mongoCursor.next();
String name = document.get("name", String.class);
Integer age = document.get("age", Integer.class);
String marry = document.get("marry", String.class);
System.out.println(name+"-"+age+"-"+marry);
}
//更新文档--一个
collection.updateOne(Filters.eq("age",18),new Document("$set",new
Document("name","xihe老师")));
//更新文档--多个
collection.updateMany(Filters.eq("age",18),new Document("$set",new
Document("name","xihe老师")));
//删除文档--删除一个
collection.deleteOne(Filters.eq("age",18));
//删除文档--删除多个
collection.deleteMany(Filters.eq("age",18));