docker安裝mongodb及java連接實戰

1.docker部署mongodb
docker run --name mongodb -d -p 27017:27017 -v /data/mongodbdata:/data/db -e MONGO_INITDB_ROOT_USERNAME=testmongo -e MONGO_INITDB_ROOT_PASSWORD=test123456 mongodb:4.0.112.項目實戰
<dependencies><dependency><groupId>org.mongodb</groupId><artifactId>mongo-java-driver</artifactId><version>3.0.4</version></dependency>
</dependencies>import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;//mongodb 連接數據庫工具類
public class MongoDBUtil {//不通過認證獲取連接數據庫對象public static MongoDatabase getConnect(){//連接到 mongodb 服務MongoClient mongoClient = new MongoClient("localhost", 27017);//連接到數據庫MongoDatabase mongoDatabase = mongoClient.getDatabase("test");//返回連接數據庫對象return mongoDatabase;}//需要密碼認證方式連接public static MongoDatabase getConnect2(){List<ServerAddress> adds = new ArrayList<>();//ServerAddress()兩個參數分別為 服務器地址 和 端口ServerAddress serverAddress = new ServerAddress("localhost", 27017);adds.add(serverAddress);List<MongoCredential> credentials = new ArrayList<>();//MongoCredential.createScramSha1Credential()三個參數分別為 用戶名 數據庫名稱 密碼MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());credentials.add(mongoCredential);//通過連接認證獲取MongoDB連接MongoClient mongoClient = new MongoClient(adds, credentials);//連接到數據庫MongoDatabase mongoDatabase = mongoClient.getDatabase("test");//返回連接數據庫對象return mongoDatabase;}
}//插入一個文檔
@Test
public void insertOneTest(){//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//要插入的數據Document document = new Document("name","張三").append("sex", "男").append("age", 18);//插入一個文檔collection.insertOne(document);
}//插入多個文檔
@Test
public void insertManyTest(){//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//要插入的數據List<Document> list = new ArrayList<>();for(int i = 1; i <= 3; i++) {Document document = new Document("name", "張三").append("sex", "男").append("age", 18);list.add(document);}//插入多個文檔collection.insertMany(list);
}//刪除與篩選器匹配的單個文檔
@Test
public void deleteOneTest(){//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//申明刪除條件Bson filter = Filters.eq("age",18);//刪除與篩選器匹配的單個文檔collection.deleteOne(filter);
}//刪除與篩選器匹配的所有文檔
@Test
public void deleteManyTest(){//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//申明刪除條件Bson filter = Filters.eq("age",18);//刪除與篩選器匹配的所有文檔collection.deleteMany(filter);
}//修改單個文檔
@Test
public void updateOneTest(){//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//修改過濾器Bson filter = Filters.eq("name", "張三");//指定修改的更新文檔Document document = new Document("$set", new Document("age", 100));//修改單個文檔collection.updateOne(filter, document);
}//修改多個文檔
@Test
public void updateManyTest(){//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//修改過濾器Bson filter = Filters.eq("name", "張三");//指定修改的更新文檔Document document = new Document("$set", new Document("age", 100));//修改多個文檔collection.updateMany(filter, document);
}//查找集合中的所有文檔
@Test
public void findTest(){//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//查找集合中的所有文檔FindIterable findIterable = collection.find();MongoCursor cursor = findIterable.iterator();while (cursor.hasNext()) {System.out.println(cursor.next());}
}//指定查詢過濾器查詢
@Test
public void FilterfindTest(){//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//指定查詢過濾器Bson filter = Filters.eq("name", "張三");//指定查詢過濾器查詢FindIterable findIterable = collection.find(filter);MongoCursor cursor = findIterable.iterator();while (cursor.hasNext()) {System.out.println(cursor.next());}
}//取出查詢到的第一個文檔
@Test
public void findTest(){//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");//查找集合中的所有文檔FindIterable findIterable = collection.find();//取出查詢到的第一個文檔Document document = (Document) findIterable.first();//打印輸出System.out.println(document);
}import com.mongodb.client.FindIterable;
import org.bson.Document;
import java.util.List;
import java.util.ArrayList;public class MongoDBPagingExample {public static void main(String[] args) {// 連接到MongoDB(同上)MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");MongoDatabase database = mongoClient.getDatabase("yourDatabaseName");MongoCollection<Document> collection = database.getCollection("yourCollectionName");//或者//獲取數據庫連接對象MongoDatabase mongoDatabase = MongoDBUtil.getConnect();//獲取集合MongoCollection<Document> collection = mongoDatabase.getCollection("user");// 分頁參數int pageNumber = 1; // 頁碼,從1開始int pageSize = 10;  // 每頁大小int skipCount = (pageNumber - 1) * pageSize; // 計算需要跳過的文檔數// 執行分頁查詢FindIterable<Document> findIterable = collection.find().skip(skipCount).limit(pageSize);List<Document> documents = new ArrayList<>();findIterable.forEach(documents::add); // 將結果添加到列表中// 輸出結果documents.forEach(doc -> System.out.println(doc.toJson()));}
}

java獲取MongoDB數據庫的名稱、表名和字段名及相關信息

import com.mongodb.client.*;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import org.bson.BsonDocument;
import org.bson.BsonValue;
import org.bson.Document;import java.util.Map;
import java.util.Objects;public class MongodbDemo {// 1.獲取MongoClient客戶端public static MongoClient getMongoClient(String url) {MongoClientURI mongoClientURI = new MongoClientURI(url);MongoClient mongoClient = new MongoClient(mongoClientURI);return mongoClient;}// 2.獲取數據庫列表public static ListDatabasesIterable<Document> getDataBases(String url) {MongoClient mongoClient = getMongoClient(url);ListDatabasesIterable<Document> listDatabasesIterable = mongoClient.listDatabases();for (Document database: listDatabasesIterable) {System.out.println("DataBase : " + database.get("name"));}close(mongoClient);return listDatabasesIterable;}// 3.獲取數據庫中的集合public static void getCollectionNames(String url) {ListDatabasesIterable<Document> listDatabasesIterable = getDataBases(url);MongoClient mongoClient = getMongoClient(url);for (Document database: listDatabasesIterable) {String databaseName = String.valueOf(database.get("name"));// 跳過系統相關表if ("admin".equals(databaseName)|| "config".equals(databaseName)|| "local".equals(databaseName)) {continue;}MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);MongoIterable<String> collectionNames = mongoDatabase.listCollectionNames();System.out.println("DataBase : " + databaseName);for (String collectionName: collectionNames) {System.out.println(" CollectionName : " + collectionName);getField(mongoDatabase, collectionName);getDocument(mongoDatabase, collectionName);}}close(mongoClient);}// 4.獲取集合中的字段及格式public static void getField(MongoDatabase mongoDatabase, String collectionName) {Document doc = mongoDatabase.getCollection(collectionName).find().first();System.out.println("Collection : " + collectionName);if (Objects.nonNull(doc)) {BsonDocument document = BsonDocument.parse(doc.toJson());for(Map.Entry<String, BsonValue> entry : document.entrySet()){BsonValue value = entry.getValue();String type = value.getBsonType().name();System.out.println("Column : " + entry.getKey() + " ==== ColumnType : " + type);}}}// 5.獲取集合中的數據public static void getDocument(MongoDatabase mongoDatabase, String collectionName) {MongoCollection<Document> collection =  mongoDatabase.getCollection(collectionName);// 查詢限制50條FindIterable<Document> findIterable = collection.find().limit(50);System.out.println("CollectionName : " + collectionName);for (Document document : findIterable) {System.out.println(document);}}// 6.關閉客戶端連接public static void close(MongoClient mongoClient) {if (Objects.nonNull(mongoClient)) {mongoClient.close();}}// 測試public static void main(String[] args) {String path = "mongodb://127.0.0.1:27017";MongoClient client = getMongoClient(path);ListDatabasesIterable<Document>  listDatabases = getDataBases(path);getCollectionNames(path);getField(client.getDatabase("testdata"), "account");getDocument(client.getDatabase("testdata"), "account");close(client);}
}
//獲取鏈接對象,參數1為url,參數2為端口號
MongoClient mongoclient=new MongoClient("127.0.0.1",27017);
//獲取所有庫名的迭代器
MongoIterable<String> list= mongoclient.listDatebaseNames();
for(String str:list){System.out.println(str);//查看所有庫名
}
//獲取鏈接對象,參數1為url,參數2為端口號
MongoClient mongoclient=new MongoClient("127.0.0.1",27017);
//獲取庫對象,參數為庫名
MongoDatabase db=mongoclient.getDatabase("school");
//獲取當前庫對象的所有集合名的迭代器
MongoIterable<String> list=db.getlistCollectionNames();
for(String str:list){System.out.println(str);//獲取所有集合名
}
//獲取集合對象,參數為集合名
MongoCollention<Document> collection=db.getCollection("student");
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;import java.util.HashSet;
import java.util.Set;public class MongoDBFieldRetriever {public static void main(String[] args) {// MongoDB連接字符串String connectionString = "mongodb://localhost:27017";String dbName = "your_database_name";String collectionName = "your_collection_name";// 創建MongoDB客戶端try (MongoClient mongoClient = MongoClients.create(connectionString)) {// 選擇數據庫和集合MongoDatabase database = mongoClient.getDatabase(dbName);MongoCollection<Document> collection = database.getCollection(collectionName);// 獲取集合中的第一個文檔MongoCursor<Document> cursor = collection.find().iterator();if (cursor.hasNext()) {Document firstDocument = cursor.next();// 獲取字段及其類型Set<String> fields = new HashSet<>();for (String key : firstDocument.keySet()) {fields.add(key + " : " + firstDocument.get(key).getClass().getSimpleName());}// 輸出結果System.out.println("Fields and their types in the collection:");for (String field : fields) {System.out.println(field);}}}}
}
1.新增數據//獲取集合對象
MongoCollection<Document> collection = db.getCollection("student");
//新增時創建一個Docuement對象,以鍵值對的形式傳入內容
Document document = new Document();
document.put("name", "黑蛋");
document.put("age", 9);
document.put("sex", "公");
//添加一條數據,沒有返回值
collection.insertOne(document);
//新增多條數據,傳入一個document集合
collection.insertMany(null);
2.修改數據//修改條件
Bson eq = Filters.eq("name","黑蛋");
//修改匹配到的第一條
UpdateResult updateOne = collection.updateOne(eq, new Document("$set",new Document("age",20)));
//修改匹配的多條
collection.updateMany(eq, null);
修改的返回值內容
AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=null}
matchedCount:代表匹配到的文檔數modifiedCount:代表被修改的文檔數upsertedId:代表修改的文檔id(主鍵)3.數據刪除//條件
Bson eq = Filters.eq("name","黑蛋");
//刪除一條符合的
DeleteResult deleteOne = collection.deleteOne(eq);
//刪除 所有符合條件的
DeleteResult deleteMany = collection.deleteMany(eq);
刪除的返回值內容
AcknowledgedDeleteResult{deletedCount=0}
deletedCount:被刪除的文檔數4.查詢數據//無條件全查
FindIterable<Document> find = collection.find();
//帶條件查詢
Bson eq = Filters.regex("name", "蛋");
FindIterable<Document> find = collection.find(eq);
查詢的結果集映射這種解析方式我們必須知道文檔中的各個字段名//全查
FindIterable<Document> find = collection.find();//創建一個實體類集合準備接收結果
List<Student>  slist = new ArrayList<Student>();
//獲取結果集迭代器對象    
MongoCursor<Document> iterator = find.iterator();while(iterator.hasNext()) {Student s =  new Student();Document next = iterator.next();s.setSname(next.getString("name"));s.setSsex(next.getString("sex"));s.setSid(next.getInteger("sid"));    //將結果添加至實體類集合slist.add(s);}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/95764.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/95764.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/95764.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Java設計模式之《工廠模式》

目錄 1、介紹 1.1、定義 1.2、優缺點 1.3、使用場景 2、實現 2.1、簡單工廠模式 2.2、工廠方法模式 2.3、抽象工廠模式 3、小結 前言 在面向對象編程中&#xff0c;創建對象實例最常用的方式就是通過 new 操作符構造一個對象實例&#xff0c;但在某些情況下&#xff0…

【異步】js中異步的實現方式 async await /Promise / Generator

JS的異步相關知識 js里面一共有以下異步的解決方案 傳統的回調 省略 。。。。 生成器 Generator 函數是 ES6 提供的一種異步編程解決方案, 語法上&#xff0c;首先可以把它理解成&#xff0c;Generator 函數是一個狀態機&#xff0c;封裝了多個內部狀態。執行 Generator 函數…

JVM字節碼文件結構

Class文件結構class文件是二進制文件&#xff0c;這里要介紹的是這個二級制文件的結構。思考&#xff1a;一個java文件編譯成class文件&#xff0c;如果要描述一個java文件&#xff0c;需要哪些信息呢&#xff1f;基本信息&#xff1a;類名、父類、實現哪些接口、方法個數、每個…

11.web api 2

5. 操作元素屬性 5.1操作元素常用屬性 &#xff1a;通過 JS 設置/修改標簽元素屬性&#xff0c;比如通過 src更換 圖片最常見的屬性比如&#xff1a; href、title、src 等5.2 操作元素樣式屬性 &#xff1a;通過 JS 設置/修改標簽元素的樣式屬性。使用 className 有什么好處&a…

java中數組和list的區別是什么?

在Java中&#xff0c;數組&#xff08;Array&#xff09;和List&#xff08;通常指java.util.List接口的實現類&#xff0c;如ArrayList、LinkedList&#xff09;是兩種常用的容器&#xff0c;但它們在設計、功能和使用場景上有顯著區別。以下從核心特性、使用方式等方面詳細對…

Python爬取推特(X)的各種數據

&#x1f31f; Hello&#xff0c;我是蔣星熠Jaxonic&#xff01; &#x1f308; 在浩瀚無垠的技術宇宙中&#xff0c;我是一名執著的星際旅人&#xff0c;用代碼繪制探索的軌跡。 &#x1f680; 每一個算法都是我點燃的推進器&#xff0c;每一行代碼都是我航行的星圖。 &#x…

Oracle數據庫文件管理與空間問題解決指南

在Oracle數據庫運維中&#xff0c;表空間、數據文件及相關日志文件的管理是保障數據庫穩定運行的核心環節。本文將系統梳理表空間與數據文件的調整、關鍵文件的移動、自動擴展配置&#xff0c;以及常見空間不足錯誤的排查解決方法&#xff0c;為數據庫管理員提供全面參考。 一、…

華為實驗綜合小練習

描述&#xff1a; 1 內網有A、B、C 三個部門。所在網段如圖所示。 2 內網服務器配置靜態IP,網關192.168.100.1。 3 sw1和R1之間使用vlan200 192.168.200.0/30 互聯。 4 R1向運營商申請企業寬帶并申請了5個公網IP&#xff1a;200.1.1.1-.5子網掩碼 255.255.255.248&#xff0c;網…

Flink面試題及詳細答案100道(1-20)- 基礎概念與架構

《前后端面試題》專欄集合了前后端各個知識模塊的面試題&#xff0c;包括html&#xff0c;javascript&#xff0c;css&#xff0c;vue&#xff0c;react&#xff0c;java&#xff0c;Openlayers&#xff0c;leaflet&#xff0c;cesium&#xff0c;mapboxGL&#xff0c;threejs&…

爬蟲逆向之滑塊驗證碼加密分析(軌跡和坐標)

本文章中所有內容僅供學習交流使用&#xff0c;不用于其他任何目的。否則由此產生的一切后果均與作者無關&#xff01;在爬蟲開發過程中&#xff0c;滑塊驗證碼常常成為我們獲取數據的一大阻礙。而滑塊驗證碼的加密方式多種多樣&#xff0c;其中軌跡加密和坐標加密是比較常見的…

微信小程序實現導航至目的地

本人做的導航頁面相關功能和效果的代碼 javascript相關 Page({data: {markers: [],latitude: , // 中心點坐標longitude: ,FIXED_LAT: 31.2304, // 1. 寫死的目標點坐標, 示例&#xff1a;上海人民廣場FIXED_LNG: 121.4737},onLoad: function () {// 如果要顯示地圖可以看onLo…

中國科學社簡史

中國科學社簡史中國科學社&#xff0c;作為中國近代史上第一個民間綜合性科學團體&#xff0c;為中國現代科學文化事業的發展做出了卓越貢獻。其歷程不僅見證了中國科學從萌芽到蓬勃發展的轉變&#xff0c;還反映了中國科學體制化的艱難探索與輝煌成就。中國科學社的起源可追溯…

若爾當型,Jordon Form

文章目錄一、相似二、若爾當型1.1 認識若爾當型1.2 凱萊-哈密頓定理 (Cayley-Hamilton Theorem)一、相似 Every matrix CB?1ABC B^{-1}ABCB?1AB has the same eigenvalues as A. These C’s are similar to A. 任意一個矩陣C&#xff0c;滿足 CB?1ABC B^{-1}ABCB?1AB 都和…

解決uni-app微信小程序編譯報錯:unexpected character `1`

問題原因在uni-app微信小程序開發中&#xff0c;當template模板中包含英文符號<或>時&#xff0c;微信小程序的編譯器會將這些符號誤認為是HTML標簽的開閉符號&#xff0c;從而導致類似unexpected character 1的編譯錯誤。錯誤示例<view class"plan-bmi">…

[Linux] RAID存儲技術

目錄 RAID實現方式 RAID 0 RAID 1 RAID 5 RAID 10 管理RAID0 創建RAID 查看RAID 格式化和掛載 刪除RAID 管理RAID1 創建RAID 查看RAID 格式化和掛載 增加熱備盤 模擬故障 刪除故障磁盤 刪除RAID 管理RAID5 創建RAID 查看RAID md5設備劃分分區 RAID實現方…

程序設計|C語言教學——C語言基礎4:進階

一、預處理指令預處理指令在編譯前執行&#xff0c;除了#include&#xff0c;還有以下常用指令&#xff1a;1. #define 宏定義無參宏&#xff1a;定義常量或代碼片段&#xff0c;編譯時直接替換&#xff08;無類型檢查&#xff09;。#define PI 3.1415926 // 定義常量 #define…

數據結構之heap算法

文章目錄前言1. heap結構概述2. push_heap3. pop_heap4. sort_heap5. make_heap前言 heap這種數據結構&#xff0c;允許用戶以任何次序將任何數據放入該結構中&#xff0c;但是最后取出數據的時候一定是權值最高&#xff08;或者最低&#xff09;的元素。主要和實現有關&#x…

MCU 軟件斷點調試注意事項!!!

——為什么調試器會在運行中改我的Flash程序&#xff1f;調試單片機時&#xff0c;很多人都有這樣的疑問&#xff1a;明明我在調試前刷進去的固件是好的&#xff0c;為什么加了一個斷點之后&#xff0c;調試器居然去改了 Flash&#xff1f; 如果我拔掉調試器&#xff0c;這個固…

啟發式合并 + 莫隊 戀戀的心跳大冒險

題目來源&#xff1a;2025 Wuhan University of Technology Programming Contest 比賽鏈接&#xff1a;Dashboard - 2025 Wuhan University of Technology Programming Contest - Codeforces 題目大意&#xff1a; Solution&#xff1a; 首先肯定要預處理出以每個節點為起點…

JCTools 無鎖并發隊列基礎:ConcurrentCircularArrayQueue

ConcurrentCircularArrayQueue ConcurrentCircularArrayQueue 是一個抽象類&#xff0c;它為基于數組的并發循環隊列提供了基礎功能。從其命名可以看出幾個關鍵特性&#xff1a;??Concurrent??&#xff1a;常指無鎖并發。??Circular Array??&#xff1a;內部使用循環數…