Java 操作MongoDB
2021/7/20 2:08:20
本文主要是介绍Java 操作MongoDB,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
mongo-java-driver操作MongoDB
- 引入MongoDB依赖
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.8.2</version> </dependency>
- 连接工具类
import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.ServerAddress; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; /** * 1.连接MongoDB数据库 * 1.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("localhost", 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); } }
- Java代码演示
import com.alibaba.fastjson.JSON; import com.example.demo.Demo.util01.MongoDBPoolUtil; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import org.bson.Document; import org.bson.types.ObjectId; import java.util.ArrayList; import java.util.List; /** * 目前使用的池连方式链接MongoDB服务器, 访问:http://localhost:27017/ * It looks like you are trying to access MongoDB over HTTP on the native driver port. */ public class Test01 { public static void main(String[] args) { // 2.操作集合 // 2.1 创建集合 /*MongoDatabase mapMongoDB = MongoDBPoolUtil.getDatabase("mapMongoDB"); mapMongoDB.createCollection("macCode01"); System.out.println("创建成功!");*/ // 2.2 获取集合 /*MongoCollection<Document> test = mapMongoDB.getCollection("macCode"); System.out.println(test.getNamespace());*/ // 输出:mapMongoDB.macCode // 2.3 删除集合 /*MongoCollection<Document> dropTest = mapMongoDB.getCollection("macCode01"); dropTest.drop(); System.out.println("删除成功!");*/ System.out.println("=====================Call Start====================="); // 调用3.1 单个文档插入 /*insertSingleDocument();*/ // 调用3.2 插入多个文档 /*insertManyDocument();*/ // 调用4.1 更新单个文档单个键 /*updateSingleDocumentSingleKey();*/ // 调用4.2 更新单个文档多个键 /*updateSingleDocumentManyKey();*/ // 调用5.1 查询所有文档 /*searchAllDocument();*/ // 调用5.2 根据ID检索文档 searchDocumentById("mapMongoDB", "macCode"); } // 3.插入文档 // 3.1 单个文档插入 private static void insertSingleDocument() { MongoCollection collection = MongoDBPoolUtil.getCollection("mapMongoDB", "macCode"); Document document = new Document(); document.append("UserName", "六个核桃").append("Age", 24).append("desc", "prefect"); collection.insertOne(document); System.out.println("=====================添加单个文档成功!====================="); } // 3.2 插入多个文档 private static void insertManyDocument() { MongoCollection collection = MongoDBPoolUtil.getCollection("mapMongoDB", "macCode"); List<Document> list = new ArrayList<>(); for (int i = 0; i < 5; i++) { Document document = new Document(); document.append("UserName", "捕获第" + i + "只瑶瑶").append("Age", 18 + i).append("desc", "prefect" + i); list.add(document); } collection.insertMany(list); System.out.println("=====================插入多个文档成功!====================="); } // 4.更新文档 // 4.1 更新单个文档单个键 更新单个文档单个key private static void updateSingleDocumentSingleKey() { MongoCollection collection = MongoDBPoolUtil.getCollection("mapMongoDB", "macCode"); collection.updateOne(Filters.eq("UserName", "六个核桃"), new Document("$set", new Document("Age", 100))); System.out.println("=====================更新单个文档单个键成功!====================="); } // 4.2 更新单个文档多个键 private static void updateSingleDocumentManyKey() { MongoCollection collection = MongoDBPoolUtil.getCollection("mapMongoDB", "macCode"); collection.updateOne(Filters.eq("UserName", "六个核桃"), new Document("$set", new Document("Age", 29).append("desc", "prefect5"))); System.out.println("=====================更新单个文档多个键成功!====================="); } // 5.查询文档 // 5.1 查询所有文档 private static void searchAllDocument() { Integer sum = 0; MongoCollection collection = MongoDBPoolUtil.getCollection("mapMongoDB", "macCode"); // 返回的是一个迭代器 FindIterable<Document> iterable = collection.find(); for (Document document : iterable) { sum++; System.out.println(JSON.toJSON(document)); // System.out.println("循环第" + sum + "条数据为: " + document.get("UserName") + ",今年" + document.get("Age") + "岁!"); } System.out.println("=====================查询所有文档成功!====================="); /* 输出 循环第1条数据为: 露露,今年24岁! 循环第2条数据为: 捕获第0只瑶瑶,今年18岁! 循环第3条数据为: 捕获第1只瑶瑶,今年19岁! 循环第4条数据为: 捕获第2只瑶瑶,今年20岁! 循环第5条数据为: 捕获第3只瑶瑶,今年21岁! 循环第6条数据为: 捕获第4只瑶瑶,今年22岁!*/ } // 5.2 根据_id查询文档 private static void searchDocumentById(String database, String collection1) { MongoCollection collection = MongoDBPoolUtil.getCollection(database, collection1); FindIterable<Document> iterable = collection.find(Filters.eq("_id", new ObjectId("60f14e1922aa312798d04128"))); //返回的是一个迭代器 MongoCursor<Document> cursor = iterable.iterator(); //返回的是一个游标 while (cursor.hasNext()) { Document document = cursor.next(); System.out.println(document.get("UserName") + " " + document.get("Age")); } } }
文档出处
- 转载出处:https://www.cnblogs.com/justtodo/p/11979815.html 文章出自:青岑的博客
这篇关于Java 操作MongoDB的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-14动态路由项目实战:从入门到上手
- 2024-11-14函数组件项目实战:从入门到简单应用
- 2024-11-14获取参数项目实战:新手教程与案例分析
- 2024-11-14可视化开发项目实战:新手入门教程
- 2024-11-14可视化图表项目实战:从入门到实践
- 2024-11-14路由懒加载项目实战:新手入门教程
- 2024-11-14路由嵌套项目实战:新手入门教程
- 2024-11-14全栈低代码开发项目实战:新手入门指南
- 2024-11-14全栈项目实战:新手入门教程
- 2024-11-14useRequest教程:新手快速入门指南