Java操作MongoDB數據庫的示例代碼

mongodb-driver是mongo官方推出的java連接mongoDB的驅動包,相當於JDBC驅動。

環境準備

step1:創建工程 , 引入依賴

<dependencies>
	<dependency>
		<groupId>org.mongodb</groupId>
		<artifactId>mongodb‐driver</artifactId>
		<version>3.6.3</version>
	</dependency>
</dependencies>

step2:創建測試類

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都在安全內網下,但如果將mongodb設為安全驗證模式,就需要在客戶端提供用戶名和密碼:
        // boolean auth = db.authenticate(myUserName, myPassword);
        MongoClientOptions.Builder options = new MongoClientOptions.Builder();
        options.cursorFinalizerEnabled(true);
        // 自動重連true
        // options.autoConnectRetry(true);
        // the maximum auto connect retry time
        // 連接池設置為300個連接,默認為100
        // options.maxAutoConnectRetryTime(10); 
        options.connectionsPerHost(300);
        // 連接超時,推薦>3000毫秒
        options.connectTimeout(30000);
        options.maxWaitTime(5000); 
        // 套接字超時時間,0無限制
        options.socketTimeout(0);
        // 線程隊列數,如果連接線程排滿瞭隊列就會拋出“Out of semaphores to get db”錯誤。
        options.threadsAllowedToBlockForConnectionMultiplier(5000);
        options.writeConcern(WriteConcern.SAFE);//
        options.build();
    }
 
    // =================公用用方法=================
    /**
     * 獲取DB實例 - 指定數據庫,若不存在則創建
     */
    public static MongoDatabase getDB(String dbName) {
        if (dbName != null && !"".equals(dbName)) {
            MongoDatabase database = mongoClient.getDatabase(dbName);
            return database;
        }
        return null;
    }
 
    /**
     * 獲取指定數據庫下的collection對象
     */
    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.數據庫操作

1.1獲取所有數據庫

//獲取所有數據庫
  @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.刪除數據庫

//刪除數據庫
  @Test
  public void dropDB(){
      //連接到數據庫
      MongoDatabase mongoDatabase =  getDB("test");
      mongoDatabase.drop();
  }

2.文檔操作

2.1插入文檔

1.插入單個文檔

//插入一個文檔
@Test
public void insertOneTest(){
    //獲取集合
    MongoCollection<Document> collection = getCollection("books","book");
    //要插入的數據
    Document document = new Document("id",1)
            .append("name", "哈姆雷特")
            .append("price", 67);
    //插入一個文檔
    collection.insertOne(document);
    System.out.println(document.get("_id"));
}

2.插入多個文檔

//插入多個文檔
  @Test
  public void insertManyTest(){
      //獲取集合
      MongoCollection<Document> collection = getCollection("books","book");
      //要插入的數據
      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);
      }
      //插入多個文檔
      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.構建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,Filters提供瞭一系列查詢條件的靜態方法,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.統計查詢

//集合的文檔數統計
    @Test
    public void getCountTest() {
        //獲取集合
        MongoCollection<Document> collection = getCollection("books","book");
        //獲取集合的文檔數
        Bson filter = Filters.gt("price", 30);
        int count = (int)collection.count(filter);
        System.out.println("價錢大於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("----------取出查詢到的第一個文檔-----------------");
    //取出查詢到的第一個文檔
    Document document = (Document) findIterable.first();
    //打印輸出
    System.out.println(document);
}

2.4修改文檔

//修改文檔
  @Test
  public void updateTest(){
      //獲取集合
      MongoCollection<Document> collection = getCollection("books","book");
      //修改id=2的文檔    通過過濾器Filters,Filters提供瞭一系列查詢條件的靜態方法
      Bson filter = Filters.eq("id", 2);
      //指定修改的更新文檔
      Document document = new Document("$set", new Document("price", 44));
      //修改單個文檔
      collection.updateOne(filter, document);
      //修改多個文檔
    // collection.updateMany(filter, document);
      //修改全部文檔
      //collection.updateMany(new BasicDBObject(),document);
  }

2.5 刪除文檔

//刪除與篩選器匹配的單個文檔
  @Test
  public void deleteOneTest(){
      //獲取集合
      MongoCollection<Document> collection = getCollection("books","book");
      //申明刪除條件
      Bson filter = Filters.eq("id",3);
      //刪除與篩選器匹配的單個文檔
      collection.deleteOne(filter);
 
      //刪除與篩選器匹配的所有文檔
     // collection.deleteMany(filter);
 
      System.out.println("--------刪除所有文檔----------");
      //刪除所有文檔
     // collection.deleteMany(new Document());
  }

以上就是Java操作MongoDB的示例代碼的詳細內容,更多關於Java操作MongoDB的資料請關註WalkonNet其它相關文章!

推薦閱讀: