引入依赖:
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.8.2</version> </dependency>
1、连接MongoDB数据库
1)直连方式
public class MongoDBUtil { private static MongoClient client = null; static { if(client==null){ client = new MongoClient("192.168.3.56", 27017); } } //获取MongoDB数据库 public static MongoDatabase getDatabase(String databaseName){ return client.getDatabase(databaseName); } //获取Mongo集合 public static MongoCollection getCollection(String databaseName,String collectionName){ return getDatabase(databaseName).getCollection(collectionName); } }
2)直连方式支持用户认证
/** * @author houChen * @date 2021/7/10 17:34 * @Description: 创建MongoDB拦截,使用用户认证 */ public class MongoDBAuthUtil { private static MongoClient client = null; static { if(client==null){ //创建一个用户认证信息 MongoCredential credential = MongoCredential.createCredential("itsxt","develope","itsxtpwd".toCharArray()); //封装MongoDB的地址和端口 ServerAddress address = new ServerAddress("192.168.3.56", 27017); //方法过时是由于现在推荐池连的方式 client = new MongoClient(address, Arrays.asList(credential)); } } //获取MongoDB数据库 public static MongoDatabase getDatabase(String databaseName){ return client.getDatabase(databaseName); } //获取Mongo集合 public static MongoCollection getCollection(String databaseName,String collectionName){ return getDatabase(databaseName).getCollection(collectionName); } }
3)池连方式
public class MongoDBPoolUtil { private static MongoClient client = null; static { if(client==null){ MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); //设置每个连接地址的最大连接数 builder.connectionsPerHost(10); //设置连接的超时时间 builder.connectTimeout(5000); //设置读写的超时时间 builder.socketTimeout(5000); ServerAddress address = new ServerAddress("192.168.3.56", 27017); client = new MongoClient(address,builder.build()); } } //获取MongoDB数据库 public static MongoDatabase getDatabase(String databaseName){ return client.getDatabase(databaseName); } //获取Mongo集合 public static MongoCollection getCollection(String databaseName, String collectionName){ return getDatabase(databaseName).getCollection(collectionName); } }
4)池连方式支持认证
/** * @author houChen * @date 2021/7/10 18:08 * @Description: 支持用户认证的池连 */ public class MongoDBPoolAuthUtil { private static MongoClient client = null; static { if(client==null){ MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); //设置每个连接地址的最大连接数 builder.connectionsPerHost(10); //设置连接的超时时间 builder.connectTimeout(5000); //设置读写的超时时间 builder.socketTimeout(5000); //创建一个用户认证信息 MongoCredential credential = MongoCredential.createCredential("itsxt","develope","itsxtpwd".toCharArray()); //封装MongoDB的地址和端口 ServerAddress address = new ServerAddress("192.168.3.56", 27017); client = new MongoClient(address,credential,builder.build()); } } //获取MongoDB数据库 public static MongoDatabase getDatabase(String databaseName){ return client.getDatabase(databaseName); } //获取Mongo集合 public static MongoCollection getCollection(String databaseName, String collectionName){ return getDatabase(databaseName).getCollection(collectionName); } }
2、操作集合
1)创建集合
MongoDatabase develope = MongoDBPoolUtil.getDatabase("develope");
develope.createCollection("test1");
2)获取集合
MongoCollection<Document> test = develope.getCollection("test");
System.out.println(test.getNamespace());
3)删除集合
MongoCollection<Document> test = develope.getCollection("test1");
test.drop();
3、插入文档
1)单个文档插入
public void insertSingleDocument(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); Document document = new Document(); document.append("username","liss").append("age",18 ).append("desc", "prefect"); collection.insertOne(document); }
2)插入多个文档
public void insertManyDocument(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); List<Document> list = new ArrayList<Document>(); for(int i=0;i<5;i++){ Document document = new Document(); document.append("username","liss"+i).append("age",18+i ).append("desc", "prefect"+i); list.add(document); } collection.insertMany(list); }
4、更新文档
1)更新单个文档单个键
/* 更新单个文档单个key */ public void updateSingleDocumentSingleKey(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); collection.updateOne(Filters.eq("username","liss"), new Document("$set",new Document("userage",100))); }
2)更新单个文档多个键
/* 更新单个文档多个键 */ public void updateSingleDocumentManyKey(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); collection.updateOne(Filters.eq("username","liss"), new Document("$set",new Document("userage",100).append("age", "13"))); }
3)更新多个文档单个键
/* 更新单个文档单个个键 将username不为空的文档的age修改为100 */ public void updateManyDocumentSingleKey(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); collection.updateMany(Filters.ne("username",null), new Document("$set",new Document("desc","very good"))); }
4)更新多个文档的多个键
/* 更新多个文档多个键 将username不为空的文档的age修改为3岁,desc修改为哈哈哈哈 */ public void updateManyDocumentManyKey(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); collection.updateMany(Filters.ne("username",null), new Document("$set",new Document("age","3岁").append("desc", "哈哈哈哈"))); }
5)更新文档的数组
/* 更新文档的数组 将username为lisi的insterts数组中添加art */ public void updateArray(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); collection.updateOne(Filters.eq("username", "liss"), new Document("$push",new Document("insterts","art"))); }
5、查询文档
1)查询所有文档
public void searchAllDocument(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); FindIterable<Document> iterable = collection.find(); //返回的是一个迭代器 MongoCursor<Document> cursor = iterable.iterator(); //返回的是一个游标 while (cursor.hasNext()){ Document document = cursor.next(); System.out.println(document.get("username")+" "+document.get("age")); } }
2)根据_id查询文档
/* 根据_id查询文档 */ public void searchDocumentById(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); FindIterable<Document> iterable = collection.find(Filters.eq("_id",new ObjectId("60ea475b28339539c8b814f4"))); //返回的是一个迭代器 MongoCursor<Document> cursor = iterable.iterator(); //返回的是一个游标 while (cursor.hasNext()){ Document document = cursor.next(); System.out.println(document.get("username")+" "+document.get("age")); } }
3)查询多个文档 $gt
/* 查询多个文档 $gt 查询年龄大于19的文档 */ public void searchDocumentByCondition(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); FindIterable<Document> iterable = collection.find(Filters.gt("age",19)); //返回的是一个迭代器 MongoCursor<Document> cursor = iterable.iterator(); //返回的是一个游标 while (cursor.hasNext()){ Document document = cursor.next(); System.out.println(document.get("username")+" "+document.get("age")); } }
4)查询多个文档 $type
/* 查询多个文档 $type 查询age为number文档 */ public void searchDocumentByType(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); FindIterable<Document> iterable = collection.find(Filters.type("age","number")); //返回的是一个迭代器 MongoCursor<Document> cursor = iterable.iterator(); //返回的是一个游标 while (cursor.hasNext()){ Document document = cursor.next(); System.out.println(document.get("username")+" "+document.get("age")); } }
5)查询多个文档 $in $nin
/* 查询多个文档 $in 查询username为liss,liss1,liss2文档 $nin=>表示不在这个数组中的文档 · */ public void searchDocumentByIn(){ MongoCollection collection = MongoDBPoolUtil.getCollection("develope","test1"); FindIterable<Document> iterable = collection.find(Filters.in("username","liss","liss1","liss2")); //返回的是一个迭代器 MongoCursor<Document> cursor = iterable.iterator(); //返回的是一个游标 while (cursor.hasNext()){ Document document = cursor.next(); System.out.println(document.get("username")+" "+document.get("age")); } }