Java操作MongoDB數(shù)據(jù)庫(kù)的示例代碼
mongodb-driver是mongo官方推出的java連接mongoDB的驅(qū)動(dòng)包,相當(dāng)于JDBC驅(qū)動(dòng)。
環(huán)境準(zhǔn)備
step1:創(chuàng)建工程 , 引入依賴(lài)
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb‐driver</artifactId> <version>3.6.3</version> </dependency> </dependencies>
step2:創(chuàng)建測(cè)試類(lèi)
import com.mongodb.*; import com.mongodb.client.*; import com.mongodb.client.model.Filters; import org.bson.Document; import org.bson.conversions.Bson; import org.junit.Test; import java.util.ArrayList; import java.util.List; public class MogoDBTest { private static MongoClient mongoClient; static { System.out.println("===============MongoDBUtil初始化========================"); mongoClient = new MongoClient("127.0.0.1", 27017); // 大多使用mongodb都在安全內(nèi)網(wǎng)下,但如果將mongodb設(shè)為安全驗(yàn)證模式,就需要在客戶(hù)端提供用戶(hù)名和密碼: // boolean auth = db.authenticate(myUserName, myPassword); MongoClientOptions.Builder options = new MongoClientOptions.Builder(); options.cursorFinalizerEnabled(true); // 自動(dòng)重連true // options.autoConnectRetry(true); // the maximum auto connect retry time // 連接池設(shè)置為300個(gè)連接,默認(rèn)為100 // options.maxAutoConnectRetryTime(10); options.connectionsPerHost(300); // 連接超時(shí),推薦>3000毫秒 options.connectTimeout(30000); options.maxWaitTime(5000); // 套接字超時(shí)時(shí)間,0無(wú)限制 options.socketTimeout(0); // 線(xiàn)程隊(duì)列數(shù),如果連接線(xiàn)程排滿(mǎn)了隊(duì)列就會(huì)拋出“Out of semaphores to get db”錯(cuò)誤。 options.threadsAllowedToBlockForConnectionMultiplier(5000); options.writeConcern(WriteConcern.SAFE);// options.build(); } // =================公用用方法================= /** * 獲取DB實(shí)例 - 指定數(shù)據(jù)庫(kù),若不存在則創(chuàng)建 */ public static MongoDatabase getDB(String dbName) { if (dbName != null && !"".equals(dbName)) { MongoDatabase database = mongoClient.getDatabase(dbName); return database; } return null; } /** * 獲取指定數(shù)據(jù)庫(kù)下的collection對(duì)象 */ public static MongoCollection<Document> getCollection(String dbName, String collName) { if (null == collName || "".equals(collName)) { return null; } if (null == dbName || "".equals(dbName)) { return null; } MongoCollection<Document> collection = mongoClient .getDatabase(dbName) .getCollection(collName); return collection; } }
1.數(shù)據(jù)庫(kù)操作
1.1獲取所有數(shù)據(jù)庫(kù)
//獲取所有數(shù)據(jù)庫(kù) @Test public void getAllDBNames(){ MongoIterable<String> dbNames = mongoClient.listDatabaseNames(); for (String s : dbNames) { System.out.println(s); } }
1.2獲取指定庫(kù)的所有集合名
//獲取指定庫(kù)的所有集合名 @Test public void getAllCollections(){ MongoIterable<String> colls = getDB("books").listCollectionNames(); for (String s : colls) { System.out.println(s); } }
1.3.刪除數(shù)據(jù)庫(kù)
//刪除數(shù)據(jù)庫(kù) @Test public void dropDB(){ //連接到數(shù)據(jù)庫(kù) MongoDatabase mongoDatabase = getDB("test"); mongoDatabase.drop(); }
2.文檔操作
2.1插入文檔
1.插入單個(gè)文檔
//插入一個(gè)文檔 @Test public void insertOneTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //要插入的數(shù)據(jù) Document document = new Document("id",1) .append("name", "哈姆雷特") .append("price", 67); //插入一個(gè)文檔 collection.insertOne(document); System.out.println(document.get("_id")); }
2.插入多個(gè)文檔
//插入多個(gè)文檔 @Test public void insertManyTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //要插入的數(shù)據(jù) List<Document> list = new ArrayList<>(); for(int i = 1; i <= 15; i++) { Document document = new Document("id",i) .append("name", "book"+i) .append("price", 20+i); list.add(document); } //插入多個(gè)文檔 collection.insertMany(list); }
2.2查詢(xún)文檔
2.2.1基本查詢(xún)
1.查詢(xún)集合所有文檔
@Test public void findAllTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //查詢(xún)集合的所有文檔 FindIterable findIterable= collection.find(); MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } }
2.條件查詢(xún)
@Test public void findConditionTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //方法1.構(gòu)建BasicDBObject 查詢(xún)條件 id大于2,小于5 BasicDBObject queryCondition=new BasicDBObject(); queryCondition.put("id", new BasicDBObject("$gt", 2)); queryCondition.put("id", new BasicDBObject("$lt", 5)); //查詢(xún)集合的所有文 通過(guò)price升序排序 FindIterable findIterable= collection.find(queryCondition).sort(new BasicDBObject("price",1)); //方法2.通過(guò)過(guò)濾器Filters,F(xiàn)ilters提供了一系列查詢(xún)條件的靜態(tài)方法,id大于2小于5,通過(guò)id升序排序查詢(xún) //Bson filter=Filters.and(Filters.gt("id", 2),Filters.lt("id", 5)); //FindIterable findIterable= collection.find(filter).sort(Sorts.orderBy(Sorts.ascending("id"))); //查詢(xún)集合的所有文 MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } }
2.2.2 投影查詢(xún)
@Test public void findAllTest3(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //查詢(xún)id等于1,2,3,4的文檔 Bson fileter=Filters.in("id",1,2,3,4); //查詢(xún)集合的所有文檔 FindIterable findIterable= collection.find(fileter).projection(new BasicDBObject("id",1).append("name",1).append("_id",0)); MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } }
2.3分頁(yè)查詢(xún)
2.3.1.統(tǒng)計(jì)查詢(xún)
//集合的文檔數(shù)統(tǒng)計(jì) @Test public void getCountTest() { //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //獲取集合的文檔數(shù) Bson filter = Filters.gt("price", 30); int count = (int)collection.count(filter); System.out.println("價(jià)錢(qián)大于30的count==:"+count); }
2.3.2分頁(yè)列表查詢(xún)
//分頁(yè)查詢(xún) @Test public void findByPageTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //分頁(yè)查詢(xún) 跳過(guò)0條,返回前10條 FindIterable findIterable= collection.find().skip(0).limit(10); MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } System.out.println("----------取出查詢(xún)到的第一個(gè)文檔-----------------"); //取出查詢(xún)到的第一個(gè)文檔 Document document = (Document) findIterable.first(); //打印輸出 System.out.println(document); }
2.4修改文檔
//修改文檔 @Test public void updateTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //修改id=2的文檔 通過(guò)過(guò)濾器Filters,F(xiàn)ilters提供了一系列查詢(xún)條件的靜態(tài)方法 Bson filter = Filters.eq("id", 2); //指定修改的更新文檔 Document document = new Document("$set", new Document("price", 44)); //修改單個(gè)文檔 collection.updateOne(filter, document); //修改多個(gè)文檔 // collection.updateMany(filter, document); //修改全部文檔 //collection.updateMany(new BasicDBObject(),document); }
2.5 刪除文檔
//刪除與篩選器匹配的單個(gè)文檔 @Test public void deleteOneTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //申明刪除條件 Bson filter = Filters.eq("id",3); //刪除與篩選器匹配的單個(gè)文檔 collection.deleteOne(filter); //刪除與篩選器匹配的所有文檔 // collection.deleteMany(filter); System.out.println("--------刪除所有文檔----------"); //刪除所有文檔 // collection.deleteMany(new Document()); }
以上就是Java操作MongoDB的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Java操作MongoDB的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringMVC整合SpringSession 實(shí)現(xiàn)sessiong
這篇文章主要介紹了SpringMVC整合SpringSession 實(shí)現(xiàn)session的實(shí)例代碼,本文通過(guò)實(shí)例相結(jié)合的形式給大家介紹的非常詳細(xì),需要的朋友參考下吧2018-04-04Mapper層繼承BaseMapper<T>需要引入的pom依賴(lài)方式
這篇文章主要介紹了Mapper層繼承BaseMapper<T>需要引入的pom依賴(lài)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01SpringBoot?自定義starter?yaml提示失效問(wèn)題及解決方法
在自定義starter后,必不可少會(huì)有properties配置參數(shù)需要指定,而在有時(shí)又不知道為什么出現(xiàn)這個(gè)問(wèn)題,這篇文章主要介紹了SpringBoot?自定義starter?yaml提示失效問(wèn)題,需要的朋友可以參考下2022-12-12Spring Boot 整合 TKMybatis 二次簡(jiǎn)化持久層代碼的實(shí)現(xiàn)
這篇文章主要介紹了Spring Boot 整合 TKMybatis 二次簡(jiǎn)化持久層代碼的實(shí)現(xiàn),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01java.net.MalformedURLException異常的解決方法
下面小編就為大家?guī)?lái)一篇java.net.MalformedURLException異常的解決方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05Java 創(chuàng)建兩個(gè)線(xiàn)程模擬對(duì)話(huà)并交替輸出實(shí)現(xiàn)解析
這篇文章主要介紹了Java 創(chuàng)建兩個(gè)線(xiàn)程模擬對(duì)話(huà)并交替輸出實(shí)現(xiàn)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10Java發(fā)送報(bào)文與接收?qǐng)?bào)文的實(shí)例代碼
這篇文章主要介紹了Java發(fā)送報(bào)文與接收?qǐng)?bào)文,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03restemplate請(qǐng)求亂碼之content-encoding=“gzip“示例詳解
RestTemplate從Spring3.0開(kāi)始支持的一個(gè)HTTP請(qǐng)求工具,它提供了常見(jiàn)的REST請(qǐng)求方案的模板,及一些通用的請(qǐng)求執(zhí)行方法 exchange 以及 execute,接下來(lái)通過(guò)本文給大家介紹restemplate請(qǐng)求亂碼之content-encoding=“gzip“,需要的朋友可以參考下2024-03-03