依赖
首先新建maven项目添加依赖
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.4</version>
</dependency>
连接数据库
不认证直接连接
//默认地址127.0.0.1 默认ip27017
MongoClient mongoClient = new MongoClient();
MongoClient mongoClient = new MongoClient("127.0.0.1");
MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
MongoClient mongoClient = new MongoClient("127.0.0.1:27017");
认证连接
List<ServerAddress> adds = new ArrayList<>();
//服务器地址\端口
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
adds.add(serverAddress);
List<MongoCredential> credentials = new ArrayList<>();
//用户名\数据库名称\密码
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("test123", "mydata", "123".toCharArray());
credentials.add(mongoCredential);
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(adds, credentials);
连接数据库
//查询所有的Database
ListDatabasesIterable<Document> list= mongoClient.listDatabases();
//连接到指定数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mydata");
数据库的增删改查
1、查询
//查询数据库所有的表
MongoIterable<String> mongoIterable = db.listCollectionNames();
//查询表中所有数据
MongoCollection<Document> persons = db.getCollection("persons");
//-----------------------------------------------------------
//查找集合中的所有文档
FindIterable findIterable = persons .find();
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
//-----------------------------------------------------------
//指定查询过滤器
Bson filter = Filters.eq("name", "张三");
//指定查询过滤器查询
FindIterable findIterable = persons.find(filter);
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
//-----------------------------------------------------------
//查询第一个文档
Document document = (Document) findIterable.first();
2、增加
MongoCollection<Document> persons = db.getCollection("persons");
//----------------插入一个文档--------------------------------------
Document document = new Document("name","张三").append("age", 10);
persons.insertOne(document);
//----------------插入多个文档--------------------------------------
List<Document> list = new ArrayList<>();
for(int i = 0; i < 10; i++) {
Document document = new Document("name", "张三"+i).append("age", 10+i);
list.add(document);
}
persons.insertMany(list);
3、删除
MongoCollection<Document> persons = db.getCollection("persons");
//删除条件
Bson filter = Filters.eq("age",18);
//删除一个符合文档
persons.deleteOne(filter);
//删除所有符合文档
persons.deleteMany(filter);
4、修改
MongoCollection<Document> persons = db.getCollection("persons");
//修改条件
Document document = new Document("$set", new Document("age", 100));
//修改一个文档
persons .updateOne(filter, document);
//修改全部符合文档
persons .updateMany(filter, document);