Java中連接Mongodb進行增刪改查的操作詳解
1.引入Java驅(qū)動依賴
注意:啟動服務(wù)的時候需要加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) { // 連接的url String 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
@Test public 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
@Test public void UpdateDocument(){ MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("map"); //構(gòu)造更新條件 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 query UpdateOptions 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 performed System.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
@Test public void testFindDocuments(){ MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("map"); // 創(chuàng)建檢索條件 /*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
@Test public 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); } }
到此這篇關(guān)于Java中連接Mongodb進行增刪改查的操作詳解的文章就介紹到這了,更多相關(guān)Java連接Mongodb操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實現(xiàn)的Excel列號數(shù)字與字母互相轉(zhuǎn)換功能
這篇文章主要介紹了Java實現(xiàn)的Excel列號數(shù)字與字母互相轉(zhuǎn)換功能,涉及java針對Excel相關(guān)數(shù)值與字符串操作技巧,需要的朋友可以參考下2018-03-03Spring?Cloud?Gateway?整合?knife4j?聚合接口文檔功能
這篇文章主要介紹了Spring?Cloud?Gateway?整合?knife4j?聚合接口文檔的相關(guān)知識,我們可以基于?Spring?Cloud?Gateway?網(wǎng)關(guān)?+?nacos?+?knife4j?對所有微服務(wù)項目的接口文檔進行聚合,從而實現(xiàn)我們想要的文檔管理功能,需要的朋友可以參考下2022-02-02java并發(fā)編程工具類PriorityBlockingQueue優(yōu)先級隊列
這篇文章主要為大家介紹了java并發(fā)編程工具類PriorityBlockingQueue優(yōu)先級隊列的方法示例應(yīng)用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-03-03一文了解SpringBoot是如何連接數(shù)據(jù)庫的
Spring Boot提供了一系列的開箱即用的功能和特性,使得開發(fā)人員可以快速構(gòu)建和部署應(yīng)用程序,下面這篇文章主要給大家介紹了關(guān)于SpringBoot是如何連接數(shù)據(jù)庫的相關(guān)資料,需要的朋友可以參考下2023-06-06Springboot2.x結(jié)合Mabatis3.x下Hikari連接數(shù)據(jù)庫報超時錯誤
本文針對Springboot2.x與Mybatis3.x結(jié)合使用時,Hikari連接數(shù)據(jù)庫出現(xiàn)超時錯誤的問題進行了深入分析,并提供了一系列有效的解決方法,感興趣的可以了解一下2023-11-11關(guān)于springboot集成swagger及knife4j的增強問題
這篇文章主要介紹了springboot集成swagger以及knife4j的增強,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03Java數(shù)據(jù)結(jié)構(gòu)中關(guān)于AVL樹的實現(xiàn)方法詳解
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)中關(guān)于AVL樹的實現(xiàn)方法,AVL樹是高度平衡的二叉樹,它的特點是AVL樹中任何節(jié)點的兩個子樹的高度最大差別為1,本文主要給大家介紹了Java語言如何實現(xiàn)AVL樹,需要的朋友可以參考下2024-02-02Java ArrayList與LinkedList使用方法詳解
Java中容器對象主要用來存儲其他對象,根據(jù)實現(xiàn)原理不同,主要有3類常用的容器對象:ArrayList使用數(shù)組結(jié)構(gòu)存儲容器中的元素、LinkedList使用鏈表結(jié)構(gòu)存儲容器中的元素2022-11-11