当前位置: 首页 > news >正文

Java中连接Mongodb进行操作

文章目录

  • 1.引入Java驱动依赖
  • 2.快速开始
    • 2.1 先在monsh连接建立collection
    • 2.2 java中快速开始
    • 2.3 Insert a Document
    • 2.4 Update a Document
    • 2.5 Find a Document
    • 2.6 Delete a Document

1.引入Java驱动依赖

注意:启动服务的时候需要加ip绑定
需要引入依赖

<dependency><groupId>org.mongodb</groupId><artifactId>mongodb-driver-sync</artifactId><version>5.1.0</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/org.mongodb/bson --><dependency><groupId>org.mongodb</groupId><artifactId>bson</artifactId><version>5.1.0</version></dependency><!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-core --><dependency><groupId>org.mongodb</groupId><artifactId>mongodb-driver-core</artifactId><version>5.1.0</version></dependency>

2.快速开始

2.1 先在monsh连接建立collection

db.players.insertOne({name:"palyer1",height:181,weigh:90})
{acknowledged: true,insertedId: ObjectId('665c5e0a522ef6dba6a26a13')
}
test> db.players.insertOne({name:"palyer2",height:190,weigh:100})
{acknowledged: true,insertedId: ObjectId('665c5e18522ef6dba6a26a14')
}
test> db.players.find()
[{_id: ObjectId('665c5e0a522ef6dba6a26a13'),name: 'player1',height: 181,weigh: 90},{_id: ObjectId('665c5e18522ef6dba6a26a14'),name: 'player2',height: 190,weigh: 100}
]

2.2 java中快速开始

public class QuickStart {public static void main(String[] args) {// 连接的urlString uri = "mongodb://node02:27017";try (MongoClient mongoClient = MongoClients.create(uri)) {MongoDatabase database = mongoClient.getDatabase("test");MongoCollection<Document> collection = database.getCollection("players");Document doc = collection.find(eq("name", "palyer2")).first();if (doc != null) {//{"_id": {"$oid": "665c5e18522ef6dba6a26a14"}, "name": "palyer2", "height": 190, "weigh": 100}System.out.println(doc.toJson());} else {System.out.println("No matching documents found.");}}}}

2.3 Insert a Document

 @Testpublic void InsertDocument(){MongoDatabase database = mongoClient.getDatabase("test");MongoCollection<Document> collection = database.getCollection("map");try {// 插入地图文档InsertOneResult result = collection.insertOne(new Document().append("_id", new ObjectId()).append("name", "beijing").append("longitude", "40°N").append("latitude", "116°E"));//打印文档的id//Success! Inserted document id: BsonObjectId{value=665c6424a080bb466d32e645}System.out.println("Success! Inserted document id: " + result.getInsertedId());// Prints a message if any exceptions occur during the operation} catch (MongoException me) {System.err.println("Unable to insert due to an error: " + me);}

2.4 Update a Document

 @Testpublic void UpdateDocument(){MongoDatabase database = mongoClient.getDatabase("test");MongoCollection<Document> collection = database.getCollection("map");//构造更新条件Document query = new Document().append("name",  "beijing");// 指定更新的字段Bson updates = Updates.combine(Updates.set("longitude", "40.0N"),Updates.set("latitude", "116.0E"));// Instructs the driver to insert a new document if none match the queryUpdateOptions options = new UpdateOptions().upsert(true);try {// 更新文档UpdateResult result = collection.updateOne(query, updates, options);// Prints the number of updated documents and the upserted document ID, if an upsert was performedSystem.out.println("Modified document count: " + result.getModifiedCount());System.out.println("Upserted id: " + result.getUpsertedId());} catch (MongoException me) {System.err.println("Unable to update due to an error: " + me);}}

2.5 Find a Document

 @Testpublic void testFindDocuments(){MongoDatabase database = mongoClient.getDatabase("test");MongoCollection<Document> collection = database.getCollection("map");// 创建检索条件/*Bson projectionFields = Projections.fields(Projections.include("name", "shanghai"),Projections.excludeId());*/// 匹配过滤检索文档MongoCursor<Document> cursor = collection.find(eq("name", "shanghai"))//.projection(projectionFields).sort(Sorts.descending("longitude")).iterator();// 打印检索到的文档try {while(cursor.hasNext()) {System.out.println(cursor.next().toJson());}} finally {cursor.close();}}

检索

2.6 Delete a Document

 @Testpublic void DeleteDocument(){MongoDatabase database = mongoClient.getDatabase("test");MongoCollection<Document> collection = database.getCollection("map");Bson query = eq("name", "shanghai");try {// 删除名字为shanghai的地图DeleteResult result = collection.deleteOne(query);System.out.println("Deleted document count: " + result.getDeletedCount());// 打印异常消息} catch (MongoException me) {System.err.println("Unable to delete due to an error: " + me);}}
http://www.lryc.cn/news/360716.html

相关文章:

  • LabVIEW远程开发与调试
  • C/C++|基于回调函数实现异步操作
  • Mac上搭建Python环境:深入探索与高效实践
  • 数据标准的制定落地
  • 微信小程序基础 -- 小程序UI组件(5)
  • Linux shell编程学习笔记55:hostname命令——获取或设置主机名,显示IP地址和DNS、NIS
  • 【鸟哥】Linux笔记-硬件搭配
  • 代码随想三刷数组篇
  • windows环境下重建oracle监听
  • 单元测试框架Pytest的基本操作
  • Java web应用性能分析之【java进程问题分析工具】
  • 02-2.3.2_2 单链表的查找
  • 设计模式(十四)行为型模式---访问者模式(visitor)
  • 【Matplotlib作图-3.Ranking】50 Matplotlib Visualizations, Python实现,源码可复现
  • 加入不正确的位置编码会破坏掉原本的信息吗?
  • 区块链合约开发流程
  • 建筑企业有闲置资质怎么办?
  • Java开发-特殊文本文件,日志技术
  • Django ORM深度游:探索多对一、一对一与多对多数据关系的奥秘与实践
  • 无人机路径规划:基于鸽群优化算法PIO的无人机三维路径规划MATLAB代码
  • ArcGIS属性域和子类型
  • 电子电器架构 --- 什么是域控制器?
  • 链表头部插入结点
  • k8s集群修改apiserver的ip地址
  • C语言编程技巧:深度挖掘与高效实践
  • 十_信号14 - system()
  • 【Python网络爬虫】详解python爬虫中URL资源抓取
  • AI办公自动化:用kimi批量提取音频中的标题并重命名
  • flyfish3.0.0配置避坑
  • Spring (33)CSRF(跨站请求伪造)保护