Java操作MongoDB數(shù)據(jù)庫的示例代碼
mongodb-driver是mongo官方推出的java連接mongoDB的驅(qū)動(dòng)包,相當(dāng)于JDBC驅(qū)動(dòng)。
環(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;
}
}
1.數(shù)據(jù)庫操作
1.1獲取所有數(shù)據(jù)庫
//獲取所有數(shù)據(jù)庫
@Test
public void getAllDBNames(){
MongoIterable<String> dbNames = mongoClient.listDatabaseNames();
for (String s : dbNames) {
System.out.println(s);
}
}
1.2獲取指定庫的所有集合名
//獲取指定庫的所有集合名
@Test
public void getAllCollections(){
MongoIterable<String> colls = getDB("books").listCollectionNames();
for (String s : colls) {
System.out.println(s);
}
}
1.3.刪除數(shù)據(jù)庫
//刪除數(shù)據(jù)庫
@Test
public void dropDB(){
//連接到數(shù)據(jù)庫
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查詢文檔
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分頁查詢
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);
}
2.4修改文檔
//修改文檔
@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);
}
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í)例代碼,本文通過實(shí)例相結(jié)合的形式給大家介紹的非常詳細(xì),需要的朋友參考下吧2018-04-04
Mapper層繼承BaseMapper<T>需要引入的pom依賴方式
這篇文章主要介紹了Mapper層繼承BaseMapper<T>需要引入的pom依賴方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
SpringBoot?自定義starter?yaml提示失效問題及解決方法
在自定義starter后,必不可少會(huì)有properties配置參數(shù)需要指定,而在有時(shí)又不知道為什么出現(xiàn)這個(gè)問題,這篇文章主要介紹了SpringBoot?自定義starter?yaml提示失效問題,需要的朋友可以參考下2022-12-12
Spring Boot 整合 TKMybatis 二次簡化持久層代碼的實(shí)現(xiàn)
這篇文章主要介紹了Spring Boot 整合 TKMybatis 二次簡化持久層代碼的實(shí)現(xiàn),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
java.net.MalformedURLException異常的解決方法
下面小編就為大家?guī)硪黄猨ava.net.MalformedURLException異常的解決方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-05-05
Java 創(chuàng)建兩個(gè)線程模擬對(duì)話并交替輸出實(shí)現(xiàn)解析
這篇文章主要介紹了Java 創(chuàng)建兩個(gè)線程模擬對(duì)話并交替輸出實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
Java發(fā)送報(bào)文與接收?qǐng)?bào)文的實(shí)例代碼
這篇文章主要介紹了Java發(fā)送報(bào)文與接收?qǐng)?bào)文,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
restemplate請(qǐng)求亂碼之content-encoding=“gzip“示例詳解
RestTemplate從Spring3.0開始支持的一個(gè)HTTP請(qǐng)求工具,它提供了常見的REST請(qǐng)求方案的模板,及一些通用的請(qǐng)求執(zhí)行方法 exchange 以及 execute,接下來通過本文給大家介紹restemplate請(qǐng)求亂碼之content-encoding=“gzip“,需要的朋友可以參考下2024-03-03

