您好,登錄后才能下訂單哦!
如何使用Java操作MongoDB數(shù)據(jù)庫?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
1.SpringMVC,Spring Web MVC是一種基于Java的實(shí)現(xiàn)了Web MVC設(shè)計(jì)模式的請(qǐng)求驅(qū)動(dòng)類型的輕量級(jí)Web框架。2.Shiro,Apache Shiro是Java的一個(gè)安全框架。3.Mybatis,MyBatis 是支持普通 SQL查詢,存儲(chǔ)過程和高級(jí)映射的優(yōu)秀持久層框架。4.Dubbo,Dubbo是一個(gè)分布式服務(wù)框架。5.Maven,Maven是個(gè)項(xiàng)目管理和構(gòu)建自動(dòng)化工具。6.RabbitMQ,RabbitMQ是用Erlang實(shí)現(xiàn)的一個(gè)高并發(fā)高可靠AMQP消息隊(duì)列服務(wù)器。7.Ehcache,EhCache 是一個(gè)純Java的進(jìn)程內(nèi)緩存框架。
環(huán)境準(zhǔn)備
step1:創(chuàng)建工程 , 引入依賴
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb‐driver</artifactId> <version>3.6.3</version> </dependency> </dependencies>
step2:創(chuàng)建測(cè)試類
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)證模式,就需要在客戶端提供用戶名和密碼: // 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無限制 options.socketTimeout(0); // 線程隊(duì)列數(shù),如果連接線程排滿了隊(duì)列就會(huì)拋出“Out of semaphores to get db”錯(cuò)誤。 options.threadsAllowedToBlockForConnectionMultiplier(5000); options.writeConcern(WriteConcern.SAFE);// options.build(); } // =================公用用方法================= /** * 獲取DB實(shí)例 - 指定數(shù)據(jù)庫,若不存在則創(chuàng)建 */ public static MongoDatabase getDB(String dbName) { if (dbName != null && !"".equals(dbName)) { MongoDatabase database = mongoClient.getDatabase(dbName); return database; } return null; } /** * 獲取指定數(shù)據(jù)庫下的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; } }
//獲取所有數(shù)據(jù)庫 @Test public void getAllDBNames(){ MongoIterable<String> dbNames = mongoClient.listDatabaseNames(); for (String s : dbNames) { System.out.println(s); } }
//獲取指定庫的所有集合名 @Test public void getAllCollections(){ MongoIterable<String> colls = getDB("books").listCollectionNames(); for (String s : colls) { System.out.println(s); } }
//刪除數(shù)據(jù)庫 @Test public void dropDB(){ //連接到數(shù)據(jù)庫 MongoDatabase mongoDatabase = getDB("test"); mongoDatabase.drop(); }
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.1基本查詢
1.查詢集合所有文檔
@Test public void findAllTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //查詢集合的所有文檔 FindIterable findIterable= collection.find(); MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } }
2.條件查詢
@Test public void findConditionTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //方法1.構(gòu)建BasicDBObject 查詢條件 id大于2,小于5 BasicDBObject queryCondition=new BasicDBObject(); queryCondition.put("id", new BasicDBObject("$gt", 2)); queryCondition.put("id", new BasicDBObject("$lt", 5)); //查詢集合的所有文 通過price升序排序 FindIterable findIterable= collection.find(queryCondition).sort(new BasicDBObject("price",1)); //方法2.通過過濾器Filters,F(xiàn)ilters提供了一系列查詢條件的靜態(tài)方法,id大于2小于5,通過id升序排序查詢 //Bson filter=Filters.and(Filters.gt("id", 2),Filters.lt("id", 5)); //FindIterable findIterable= collection.find(filter).sort(Sorts.orderBy(Sorts.ascending("id"))); //查詢集合的所有文 MongoCursor cursor = findIterable.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } }
2.2.2 投影查詢
@Test public void findAllTest3(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //查詢id等于1,2,3,4的文檔 Bson fileter=Filters.in("id",1,2,3,4); //查詢集合的所有文檔 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.1.統(tǒng)計(jì)查詢
//集合的文檔數(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à)錢大于30的count==:"+count); }
2.3.2分頁列表查詢
//分頁查詢 @Test public void findByPageTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //分頁查詢 跳過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("----------取出查詢到的第一個(gè)文檔-----------------"); //取出查詢到的第一個(gè)文檔 Document document = (Document) findIterable.first(); //打印輸出 System.out.println(document); }
//修改文檔 @Test public void updateTest(){ //獲取集合 MongoCollection<Document> collection = getCollection("books","book"); //修改id=2的文檔 通過過濾器Filters,F(xiàn)ilters提供了一系列查詢條件的靜態(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); }
//刪除與篩選器匹配的單個(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()); }
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。