1. 程式人生 > >【MongoDb學習之路】Java利用MongoClient類連線MongoDB資料庫

【MongoDb學習之路】Java利用MongoClient類連線MongoDB資料庫

專案需要 mongo-java-driver-3.0.2 .jar 

【重點看加粗字型,方法體中註釋的都是系統連線引數】

package cn.com.mongodb;


import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;

/**
 * JAVA連結mongodb資料庫
 *
 * @author Admin Song
 *
 */
public class ConnMongoDB {
    /**
     * 連結的ip
     */
    private static final String HOST = "localhost";

    
    /**
     * 埠
     */
    private static final int PORT = 27017;
    
    /**
     * 使用者名稱
     */
    private static final String USER_NAME = "";
    
    /**
     * 密碼
     */
    private static final String PASSWORD = "";
    
    /**
     * 資料庫名
     */
    private static final String DATA_BASENAME= "Test";

    
    /**
     * 表名
     */
    private static final String TABLE_NAME= "song";
    
    
    /**
     * 查詢一個表中所有的內容
     * @throws Exception
     */
    public void mongoDB() throws Exception {
        //mongoClient 連線伺服器端 Dubeg引數:
        //Mongo{options=MongoClientOptions{description='null', readPreference=primary, writeConcern=WriteConcern{w=1, wtimeout=0, fsync=false, j=false, cod
[email protected]
858a86c0, minConnectionsPerHost=0, maxConnectionsPerHost=100, threadsAllowedToBlockForConnectionMultiplier=5, serverSelectionTimeout=30000, maxWaitTime=120000, maxConnectionIdleTime=0, maxConnectionLifeTime=0, connectTimeout=10000, socketTimeout=0, socketKeepAlive=false, sslEnabled=false, sslInvalidHostNamesAllowed=false, alwaysUseMBeans=false, heartbeatFrequency=10000, minHeartbeatFrequency=500, heartbeatConnectTimeout=20000, heartbeatSocketTimeout=20000, localThreshold=15, requiredReplicaSetName='null', [email protected], [email protected], [email protected], cursorFinalizerEnabled=true, connectionPoolSettings=ConnectionPoolSettings{maxSize=100, minSize=0, maxWaitQueueSize=500, maxWaitTimeMS=120000, maxConnectionLifeTimeMS=0, maxConnectionIdleTimeMS=0, maintenanceInitialDelayMS=0, maintenanceFrequencyMS=60000}, socketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=0, keepAlive=false, receiveBufferSize=0, sendBufferSize=0}, serverSettings=ServerSettings{heartbeatFrequencyMS=10000, minHeartbeatFrequencyMS=500}, heartbeatSocketSettings=SocketSettings{connectTimeoutMS=20000, readTimeoutMS=20000, keepAlive=false, receiveBufferSize=0, sendBufferSize=0}}}
        MongoClient mongoClient = new MongoClient(HOST, PORT);
        
        //db 連線資料庫 Dubeg引數:
        //DB{name='Test'}
        DB db = mongoClient.getDB(DATA_BASENAME);
        
        //dbCollection 連線表 Dubeg引數:
        //DBCollection{database=DB{name='Test'}, name='song'}
        DBCollection dbCollection = db.getCollection(TABLE_NAME);
        
        //dbCursor 查詢當前表的所有資料 Dubeg引數:
        //DBCursor{collection=DBCollection{database=DB{name='Test'}, name='song'}, find=FindOptions{, batchSize=0, limit=0, modifiers=null, projection=null, maxTimeMS=0, skip=0, sort=null, cursorType=NonTailable, noCursorTimeout=false, oplogReplay=false, partial=false}}
        DBCursor dbCursor = dbCollection.find();
        
        //迭代器檢測dbCursor序列中是否還有下一個元素
        while (dbCursor.hasNext()) {
            //如果有就讀取
            System.out.println(dbCursor.next());
        }

    }

    public static void main(String[] args) {
        
        try {
            new ConnMongoDB().mongoDB();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

//main方法執行過後就會在控制檯打印出連線表當前的所有資料

============================================================

{ "_id" : { "$oid" : "5a2ab075d7feb6ad442d9adf"} , "id" : 1.0 , "name" : "name1" , "sex" :  null }
{ "_id" : { "$oid" : "5a2ab07bd7feb6ad442d9ae0"} , "id" : 2.0 , "name" : "name2" , "sex" :  null }
{ "_id" : { "$oid" : "5a2ab080d7feb6ad442d9ae1"} , "id" : 3.0 , "name" : "name3"}
{ "_id" : { "$oid" : "5a2ab085d7feb6ad442d9ae2"} , "id" : 4.0 , "name" : "name4"}
{ "_id" : { "$oid" : "5a2ab08bd7feb6ad442d9ae3"} , "id" : 5.0 , "name" : "name5"}
{ "_id" : { "$oid" : "5a2ab090d7feb6ad442d9ae4"} , "id" : 6.0 , "name" : "name6"}
{ "_id" : { "$oid" : "5a2ac0eed7feb6ad442d9ae5"} , "id" : 7.0 , "list" : [ "aaa" , "bbb" , "ccc" , "ddd"]}
{ "_id" : { "$oid" : "5a2ac10ed7feb6ad442d9ae6"} , "id" : 8.0 , "list" : [ 111.0 , 222.0 , 333.0 , 444.0]}
{ "_id" : { "$oid" : "5a2ac2b1d7feb6ad442d9ae7"} , "id" : 9.0 , "list" : [ 1.0 , 2.0 , 3.0]}

==============================================================