【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, codecRegistry=org.bson.codecs.configuration.ProvidersCodecRegistry@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', dbDecoderFactory=com.mongodb.DefaultDBDecoder$1@3b25b88c, dbEncoderFactory=com.mongodb.DefaultDBEncoder$1@29770daa, socketFactory=javax.net.DefaultSocketFactory@4722292a, 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]}

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


你可能感兴趣的:(原创)